I know this question sounds crazy, but consider the following java snippets:
Part – I:
class Consumer implements Runnable{
private boolean shouldTerminate = false
public void run() {
while( !shouldTerminate ){
//consume and perform some operation.
}
}
public void terminate(){
this.shouldTerminate = true;
}
}
So, the first question is, should I ever need to synchronize on shouldTerminate boolean? If so why? I don’t mind missing the flag set to true for one or two cycles(cycle = 1 loop execution). And second, can a boolean variable ever be in a inconsistent state?(anything other than true or false)
Part – II of the question:
class Cache<K,V> {
private Map<K, V> cache = new HashMap<K, V>();
public V getValue(K key) {
if ( !cache.containsKey(key) ) {
synchronized(this.cache){
V value = loadValue(key)
cache.put(key, value);
}
}
return cache.get(key);
}
}
Should access to the whole map be synchronized? Is there any possibility where two threads try to run this method, with one “writer thread” halfway through the process of storing value into the map and simultaneously, a “reader thread” invoking the “contains” method. Will this cause the JVM to blow up? (I don’t mind overwriting values in the map — if two writer threads try to load at the same time)
Both of the code examples have broken concurrency.
The first one requires at least the field marked
volatileor else the other thread might never see the variable being changed (it may store its value in CPU cache or a register, and not check whether the value in memory has changed).The second one is even more broken, because the internals of
HashMapare no thread-safe and it’s not just a single value but a complex data structure – using it from many threads produces completely unpredictable results. The general rule is that both reading and writing the shared state must be synchronized. You may also useConcurrentHashMapfor better performance.