I've noticed multiple people on this discussion board mentioning that they didn't use the "synchronized" keyword at all when locking their database records.
How does one get away without doing that? I thought in the very least, you had to synchronize on the record object to make sure two threads didn't accidentally lock the record? For example, below is simplified version of my code.
I would think you'd have to synchronize because two threads can hit that if-statement before the record is locked, and thus cause two threads to believe that they've locked the same record.
How did other people get away with not doing the above? I'd love to know because the less synchronization I do, the less at risk I am for deadlock. I'd also like to know if anyone's actually submitted the assignment as that and got full points for that portion of the grading.
Joined: Dec 31, 2004
You could also use the java.util.concurrent.lock package that contains a new Lock class that may substitute the synchronized keyword.
Joined: Jul 31, 2007
Cool. But am I right in assuming that it cannot be done correctly without using either java.util.concurrent.lock or synchronized?
Joined: May 29, 2006
The synchronized keyword and the lock classes in java.util.concurrent.locks can be used pretty much interchangeably. Locks have some advantages over synchronized, though: First, they are more flexible as there are methods to specify timeout values and other stuff. Second, if you use Lock.lock() and "the lock is not available then the current thread becomes disabled for thread scheduling purposes and lies dormant until the lock has been acquired" (see SUN Java 5.0 Docs). This goes for enhanced efficiency.
There are some cases, where you can also use the wait()/notify()/notifyAll() mechanism for synchronization purposes.