Home » Java Basics » synchronized » Synchronized method and block

About Ilias Tsagklis

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

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.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar

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

  Subscribe  
Notify of