3

I am cleaning up a legacy java code and I found following construct:

final class QuiteComplexClass {
    private Object lock = new Object();

    void aMethod() {
        ...
        synchronized(lock) {
              ....
        }
    }
}

Is the special object for locking necessary here? What is difference when I used simple synchronized (this)?

I think it might by useful when the class is publicly visible and somebody may call synchronized on the class instance by mistake. But this class is package private so no external code can do that.

Zaboj Campula
  • 3,155
  • 3
  • 24
  • 42

3 Answers3

2

The difference is that if you use this as lock or mark method as synchronized then another piece of code could accidentally (or intentionally) use your QuiteComplexClass object as a lock. And it might cause your code to work incorrectly. If some other developer decides to write the code as below then your code will not be able to call synchronized methods on qcc instance while lock is being held.

synchronized(qcc) { // assuming qcc is an instance of QuiteComplexClass
   while (true); // or any other time consuming operation
}
Ivan
  • 8,508
  • 2
  • 19
  • 30
1

Is the special object for locking necessary here? What is difference when I used simple synchronized (this)?

Short answer: no, it's not necessary but aside from adding final I see little to no benefit to remove it.

I tend to like to use locking objects because they give me a more fine grained lock as opposed to locking on this. You might have a couple different lock objects in your class if you are, for example, protecting multiple collections from race conditions. One thing to sure is that you should always make sure to make the lock field final.

private final Object lock = new Object();

This said, if a class is simple and you want to make sure people know which methods are synchronized then using the keyword on the methods is very appropriate as well. As you mentioned, this is an internal class but even then, developers working on the outer class might want to know about the sync points.

Gray
  • 115,027
  • 24
  • 293
  • 354
0

No, it's unnecessary. Using a lock object is a pattern intended to avoid locking on the instance. Whether that is valuable often is a matter of opinion.

xingbin
  • 27,410
  • 9
  • 53
  • 103
Steve11235
  • 2,849
  • 1
  • 17
  • 18