Home » Java Basics » synchronized


Synchronization with multiple locks

The basic idea is to use separate locks to guard multiple independent state variables of a class, instead of having only one lock in class scope. public class Grocery { private final ArrayList fruits = new ArrayList(); private final ArrayList vegetables = new ArrayList(); public synchronized void addFruit(int index, String fruit) { fruits.add(index, fruit); } public synchronized void removeFruit(int index) ...

Read More »

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: ...

Read More »