Reputation: 4556
In Java, there are 3 threads that want to access (read-only) an immutable hashmap to do something. Is SynchronizedMap
class below the fastest solution for that purpose? If not, then what would be faster to use?
import com.carrotsearch.hppc.IntObjectMap;
import com.carrotsearch.hppc.IntObjectOpenHashMap;
public class abc {
public static void main(String[] args) {
final IntObjectMap<int[]> map = new IntObjectOpenHashMap<int[]>();
for (int i = 0; i < 4; i++) {
map.put(i, new int[] {1, 2, 3, 4, 5});
}
Thread[] threads = new Thread[3];
class SynchronizedMap {
private final Object syncObject = new Object();
public final int[] read(int i) {
final int[] value;
synchronized (syncObject) {
// code that reads-only immutable map object
value = map.get(i);
}
return value;
}
}
final SynchronizedMap syncMap = new SynchronizedMap();
class AccessMap implements Runnable {
private int id;
AccessMap(int index) { id = index; }
public void run() {
// code that reads-only immutable map object like this:
for (int i = 0; i < 4; i++) {
final int[] array = syncMap.read(i);
for (int j = 0; j < array.length; j++)
System.out.println(id + ": " + array[j] + " ");
}
}
}
for (int i = 0; i < threads.length; i++) {
threads[i] = new Thread(new AccessMap(i) {});
threads[i].start();
}
for (int i = 0; i < threads.length; i++) {
try {
threads[i].join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Upvotes: 4
Views: 1697
Reputation: 116878
Is SynchronizedMap class below the fastest solution for that purpose?
No. If the HashMap
is truly immutable/read-only then a volatile Map<...>
is the way to go.
volatile IntObjectMap<int[]> readOnlyMap = new IntObjectOpenHashMap<int[]>();
If you are starting your threads after your map is built then you don't even need the volatile
. The only time you would need the volatile
is if you are swapping in a new map that is being accessed by currently running threads.
final IntObjectMap<int[]> readOnlyMap = new IntObjectOpenHashMap<int[]>();
Upvotes: 5