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.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button