synchronized
Synchronized method and block
The first level of synchronization is on method scope:
public class HelloSync { private Map dictionary = new HashMap(); public synchronized void boringDeveloper(String key, String value) { long startTime = (new java.util.Date()).getTime(); value = value + "_"+startTime; dictionary.put(key, value); System.out.println("I did this in "+ ((new java.util.Date()).getTime() - startTime)+" miliseconds"); } }
However we should consider the basic rule of concurrency: Do not hold the lock longer than necessary.
An updated version is using synchronization in a specific block:
public class HelloSync { private Map dictionary = new HashMap(); public void boringDeveloper(String key, String value) { long startTime = (new java.util.Date()).getTime(); value = value + "_"+startTime; synchronized (dictionary) { dictionary.put(key, value); } System.out.println("I did this in "+ ((new java.util.Date()).getTime() - startTime)+" miliseconds"); } }
Related Article:
Reference: Reduce lock granularity – Concurrency optimization from our JCG partner Adrianos Dadis at Java, Integration and the virtues of source.