January 2018
Intermediate to advanced
350 pages
9h 7m
English
Surely the oldest solution, but still available in Java, the synchronized keyword allows you to ensure that methods are not concurrently executed. You just need to add it in your method definition as follows:
public class SafeData { private boolean initialized = false; private String content; public synchronized void setData(String value) { content = value; initialized = true; } public synchronized String getData() { if (!initialized) { throw new IllegalStateException("structure not initialized"); } return content; }}
This is the exact same structure as the one we just saw. But now, thanks to the synchronized keyword added to each method, the call to a method would enforce concurrent calls to other synchronized methods to wait ...
Read now
Unlock full access