This week's book giveaway is in the OCMJEA forum. We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line! See this thread for details.
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.
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.