Synchronization is not an option

I recently had an interesting discussion with a java developer around multithreading

Multithreading is one of the most complex topic in Computer Science. It’s not a surprise that very few programming languages (java and c++) offer the full power (and complexity) of thread management to the developer.

bigstock-Java-Android-source-code-101015882.jpg

Atomic assignments #

Java reference assignments are always guaranteed to be atomic for

Many developers tend to forget the first line unfortunately

The following code is therefore not correct:

public class Config {
    private long lastUpdated
    private Map<> dataMap;
    ...
    public function getConfig() {

        if(lastUpdated < 5minAgo> // ERROR: Not synchronized
            reloadConfig();

        return dataMap;
    }

    public function reloadConfig() {
        ...
        // we reload the configuration from a DB or file system
        ...

        dataMap = newlyLoadedMap; // OK!
        lastUpdated = new Date().getTime(); // ERROR: Not synchronized
    }

}

The issue here is very subtle as there is no trace or indication of synchronization in the code and we are relying solely on the JVM guarantees in terms of synchronization

Therefore this works OK:

dataMap = newlyLoadedMap; // OK!

but not for these:

lastUpdated = new Date().getTime(); // ERROR: Not synchronized
if(lastUpdated < 5minAgo> // ERROR: Not synchronized

Better solutions #

Java offers plenty of options to synchronize access to shared variables:

In our case adding the volatile keyword to our references is all we need to make our code correct and self explicatory

public class Config {
    private volatile long lastUpdated
    private volatile Map<> dataMap;
    ...
    // everything as above

}
 
2
Kudos
 
2
Kudos

Now read this

Nginx by examples: the basics

Nginx is a very popular http server/rev proxy and can be used in a multitude of situations. Knowing how to configure it can literally save your day! Getting Started # To start with let’s install the latest version of Nginx from the... Continue →