-2

Difference between the two synchronized blocks in the doThis method:

Which should be used when?

public class AClass {

private final Object lock = new Object();

public void doThis(){
    synchronized(lock){
        //do stuff
    }
}

}

and

public class BClass {

public void doThis(){
    synchronized(this){
        //do stuff
    }
}

}

When should one be used over the other?

kay
  • 451
  • 1
  • 3
  • 13
  • 2
    The first example locks on an `Object`, the second on the instance of `BClass`. That's... it. Your second question is better explained here: https://stackoverflow.com/questions/442564/avoid-synchronizedthis-in-java – Ben Jun 20 '18 at 14:36
  • 2
    You can choose which object you want to use as your lock. You just posted 2 code snippets that use different objects. That's the difference. – f1sh Jun 20 '18 at 14:37

2 Answers2

0

Always use the first one.

If you do synchronized (this), you are synchronizing on an object that any other code also has the ability to synchronize on, and thus unwittingly mess up your class’s ability to function.

If you synchronize on a private object, absolutely no one can synchronize on it except the code in your class. No one has the power to interfere with your functionality.

VGR
  • 40,506
  • 4
  • 48
  • 63
  • But so If I am doing AClass[] data and say 3 instances of AClass will be handled then we should synchronize via a private object? – kay Jun 20 '18 at 14:44
  • Yes, each should have its own object for synchronization… unless you need them to synchronize with each other, which it doesn’t sound like you do. – VGR Jun 20 '18 at 14:49
  • So if we're taking into account CarPark[] parks then we use private Object to lock onto, but if there is only one CarPark on earth then we can just use synchronized(this)? – kay Jun 20 '18 at 14:51
  • No. Outside code could still synchronize on your single CarPark instance and interfere with its ability to operate in a multi-threaded environment. – VGR Jun 20 '18 at 14:52
  • So you're saying there is never a useful need for using synchronized(lock) and we should always use synchronized(this)? (Taking into account only lock1 exists, there is no lock2) – kay Jun 20 '18 at 14:55
  • I am saying exactly the opposite. Do not use `synchronized (this)`. Always synchronize on a private object, so other classes cannot synchronize on it. – VGR Jun 20 '18 at 15:01
0

The reason to use a lock object, rather than this, is simply to give yourself flexibility and to avoid deadlocks. Note that these two reasons only come into play if different methods need to synchronize, and not against each other. Providing two lock objects then makes sense. Most of the time, just using this is fine.

Steve11235
  • 2,849
  • 1
  • 17
  • 18