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

}
 
1
Kudos
 
1
Kudos

Now read this

RC4, an old friend

Recently Microsoft Google and Mozilla announced they will drop support for RC4 in their browsers SSL implementation, but RC4 won’t disappear overnight from our everyday life despite its troubled history A closed source algorithm RC4 is a... Continue →