0

I am building a concurrent application in Java. To avoid exposing my lock object externally, I have a private final lock object:

 private final Object Lock = new Object();

I use the lock for synchronization between threads:

synchronized (Lock) {

    // Do stuff
}

I also use the lock to wait for conditions:

while (conditionIsNotMet) {

    Lock.wait();
}

Does using the same object for both concurrency patterns cause any issues? Is there anything I should watch out for when doing this?

sdgfsdh
  • 33,689
  • 26
  • 132
  • 245
  • Not sure I understand. You need to have both for the `wait()` to work. – sstan Sep 23 '15 at 19:34
  • I need `synchronized` to use `wait()`? – sdgfsdh Sep 23 '15 at 19:35
  • Try to call `wait()` outside of a `synchronized` block. What happens? – sstan Sep 23 '15 at 19:36
  • You realize that your lock Object isn't declared `static`, right? – Powerlord Sep 23 '15 at 19:36
  • 1
    @sstan Thanks (for answer see http://stackoverflow.com/questions/2779484/why-must-wait-always-be-in-synchronized-block) @Powerlord Why would I want it to be `static`? – sdgfsdh Sep 23 '15 at 19:42
  • 1
    @sstan - Disagree that this is a duplicate. Why must wait() be in a synchronized block is a different question from using a particular Lock for more than one purpose - in this case protecting a condition and simultaneously synchronizing for different purposes. – Andy Sep 23 '15 at 20:00
  • 1
    @Andy: Valid point. But, in the end, OP himself closed the question as a duplicate. – sstan Sep 23 '15 at 20:10
  • This is a difficult one. The button says "This answered my question", which it did, so I clicked it. However, I agree that the "duplicate" is actually a different (but related) question. Ask on meta? – sdgfsdh Sep 23 '15 at 20:12

1 Answers1

1

It's generally bad practice to use a Lock for more than one purpose. Generally, you should associate a Lock with your condition, and another for synchronizing access to shared data. That said, nothing prevents you from doing this.

Update: That said, you should note @sstan comment - you do need to lock the Lock prior to waiting on it. If you're also using the Lock elsewhere where it's not associated with the condition, you're asking for a deadlock.

Andy
  • 1,663
  • 10
  • 17