Explore Connect Documentation
Snippets
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
class Shared {
  static final Map<String, int[]> cache = new HashMap<>();
  private static final ReadWriteLock lock = new ReentrantReadWriteLock();
  static final Lock readLock = lock.readLock();
  static final Lock writeLock = lock.writeLock();
}
class Writer extends Producer implements Runnable {
  public void run() {
    Shared.writeLock.lock();
    try {
      int[] referenceToValue = Shared.cache.get("key");
      
      for (int i = 0; i < referenceToValue.length; i++) {
        // Update value in-place; sum will add up to length
        referenceToValue[i] = produce();
      }
    } finally {
      Shared.writeLock.unlock();
    }
  }
}
class Reader extends Consumer implements Runnable {
  public void run() {
    Shared.readLock.lock();
    try {
      consume(Shared.cache.get("key"));
    } finally {
      Shared.readLock.unlock();
    }
  }
}
// {
class Simulator {
  static void simulateWork() {
    try {
      Thread.sleep(3); // simulates work being done
    } catch (InterruptedException ex) {
      System.out.println(ex);
    }
  }
}
Press desired key combination and then press ENTER.