So it looks like this:
synchronized void add() { // some code }It is the same as:
void add() { synchronized(this){ // some code } }
When we want to synchronize on the static method we can synchronize on the class object:
static void add() { synchronized(MyClass.class){ // some code } }
But it is much more secure to synchronize on the static private object. So only our object can use this lock. On the class object which is public any thread from any piece of code could do it.
So better use this lock:
private static final Object lock = new Object(); static void add() { synchronized(lock){ // some code } }
No comments:
Post a Comment