Tuesday, October 18, 2011

Synchronized in Java

If a method or class is synchronized, it means it is thread safe.

You can make a non-synchronized collection synchronized by adding the following line:

Map m = Collections.synchronizedMap(new HashMap(...));

You can make a block of text/access to a class synchronized by doing this:

synchronized(m) {
//do something
}

If you choose option 1, make sure you use the reference return by the synchronizedMap function.
If you choose option 2, make sure you synchronize every access to that object/collection.

No comments:

Post a Comment