Java Memory Model
There are Two Aspects that are to be taken care before involving Multi-threading/Concurrency:
- The data availability to multiple threads(being static – does initialization, before class’s any action or public),If data is available then:
- In what state the variable/method/resource is shared with different threads.Being shared as lazy initialization without sync(inconsistent as two threads working may get different state) or the resource shared in a consistent state(sync).
Big Question ? Does the multiple threads required shared resource in a unique state or allows other object to modify resource and update the value.
Mostly is second case , where the object is shared to be m
Scenario:
Thread is executor of task – there can br “many task/resources” run/shared by “multiple threads” OR a “single task/resource” run by “multiple threads”.
The Conclusion boils down to the point whether the resource shared by Multiple Threads is Thread-Safe (atomic change(increment operator violates ut)—>gives consistent view (lazy initialization violates it)across threads)
Note when the change is atomic ..change incorporated in “single flow” . then consistent will be the data.
A comment from senior software engineer:
making a resorece static exposes it for access by multiple threads .. Ture but it will be prone to inconsistency if it is not thread safe..
TODO:see how there is implementation of resource/task being available to multiple threads and being executed.
to know the structure of thread call to task .
Assumption – Make /fetch threads from pool and assign the task to it. so case boils down to making the task thread safe.
Listing16.4.Thread safe Lazy Initialization.
@ThreadSafe
public class SafeLazyInitialization {
private static Resource resource;
public synchronized static Resource getInstance() {
if (resource == null)
resource = new Resource();
return resource;
}
}
Listing16.5. Example – Eager-Initialization.
@ThreadSafe
public class EagerInitialization {
private static Resource resource = new Resource();
public static Resource getResource() { return resource; }
}
Using eager initialization, shown in Listing 16.5, eliminates the synchronization cost incurred on each call to getInstance in SafeLazyInitialization
Lazy loading drawback – to be made atomic(mutual exclusive) by using sync-costly operation.
DCL-double checked Locking
Stale state vs inconsistent state was the problem with DCL