How to use ReadWriteLock?

I have the following situation.

When starting the web application, I need to download a map, which will later be used by several incoming streams. That is, requests are received, and Map is used to determine whether it contains a particular key, and if so, then the value (object) is retrieved and associated with another object.

Now, the contents of the Map change from time to time. I do not want to restart the application to restart a new situation. Instead, I want to do it dynamically.

However, while the Map is reloading (deleting all elements and replacing them with new ones), simultaneous read requests on this map are still arriving.

What should I do to prevent all read streams from accessing this Card when it reloads? How can I do this in the most efficient way, because I only need it when I reboot the Card, which will occur only occasionally (every every x weeks)?

If the above is not an option (lock), how can I make sure that when I restart my read request, they will not suffer from unexpected exceptions (since the key no longer exists or the value is no longer present or is being reloaded)?

I was given advice that ReadWriteLock can help me. Can you provide me an example of how I should use this ReadWriteLock with my readers and my author?

Thanks,
E

+5
5

:

  • ( Spring, ...).
  • , .
  • , ( ).

:

    static volatile Map<U, V> map = ....;

    // **************************

    Map<U, V> tempMap = new ...;
    load(tempMap);
    map = tempMap;

Concurrency:

  • volatile .
  • , .
  • , , .
    • , ( , - ).
    • , .
+6

, , , , .

, , .

, 2 , ; , .

+3

, , , , (, if (map.contains(key)) {V value = map.get(key); ...}). , :

static Map<U,V> map = ...;

void do() {
  Map<U,V> local = map;
  if (local.contains(key)) {
    V value = local.get(key);
    ...
  }
}

:

, . , , - , . , - , . , map.contains(key), null map.get(key) - NullPointerException. , , , ( ) .

volatile. , , (map = newMap). (local = map) ( , ), , . , , ;)

+2

KLE, . , - , - CopyOnWriteArrayList, CopyOnWriteMap. , , COWMap :

http://old.nabble.com/CopyOnWriteMap-implementation-td13018855.html

+2

javadocs JDK ReentrantReadWriteLock ReadWriteLock. , , volatile

class RWDictionary {
    private final Map<String, Data> m = new TreeMap<String, Data>();
    private final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
    private final Lock r = rwl.readLock();
    private final Lock w = rwl.writeLock();

    public Data get(String key) {
        r.lock();
        try { return m.get(key); }
        finally { r.unlock(); }
    }
    public String[] allKeys() {
        r.lock();
        try { return m.keySet().toArray(); }
        finally { r.unlock(); }
    }
    public Data put(String key, Data value) {
        w.lock();
        try { return m.put(key, value); }
        finally { w.unlock(); }
    }
    public void clear() {
        w.lock();
        try { m.clear(); }
        finally { w.unlock(); }
    }
}
+1

All Articles