Synchronized

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 ...

Get Java EE 8 High Performance now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.