In a multi-threaded environment, you need to make sure that it does not change at the same time or that you can achieve a critical memory problem because it is not synchronized in any way.
Darling, just check Api before, I think the same way too.
I thought the solution was to use the static method Collections.synchronizedMap. I expected it to return a better implementation. But if you look at the source code, you will understand that all they have is just a shell with a synchronized call on the mutex, which turns out to be the same card, not allowing reading at the same time.
There is an implementation in the Jakarta commons project called FastHashMap. This implementation has a property called fast. If fast is correct, then the read is not synchronized, and the writes will perform the following steps:
Clone the current structure Perform the modification on the clone Replace the existing structure with the modified clone public class FastSynchronizedMap implements Map, Serializable { private final Map m; private ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); . . . public V get(Object key) { lock.readLock().lock(); V value = null; try { value = m.get(key); } finally { lock.readLock().unlock(); } return value; } public V put(K key, V value) { lock.writeLock().lock(); V v = null; try { v = m.put(key, value); } finally { lock.writeLock().lock(); } return v; } . . . }
Please note that we are doing a finally try block, we want to guarantee that the lock will be released no matter what problem occurs in the block.
This implementation works well when you almost do no write operations and mostly do read operations.
Sheel source share