File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Developer Certification (SCJD/OCMJD) and the fly likes Not using synchronize?! Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Developer Certification (SCJD/OCMJD)
Bookmark "Not using synchronize?!" Watch "Not using synchronize?!" New topic

Not using synchronize?!

Jimmy Ho
Ranch Hand

Joined: Jul 31, 2007
Posts: 61
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.

public long lockRecord(long recNo) {

synchronized(record) {
if (record.locked == false) {
record.locked = true;
} else {
throw new SecurityException(...)

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.

Any ideas?
Edwin Dalorzo
Ranch Hand

Joined: Dec 31, 2004
Posts: 961
You could also use the java.util.concurrent.lock package that contains a new Lock class that may substitute the synchronized keyword.

Jimmy Ho
Ranch Hand

Joined: Jul 31, 2007
Posts: 61
Cool. But am I right in assuming that it cannot be done correctly without using either java.util.concurrent.lock or synchronized?
Alexander Duenisch

Joined: May 29, 2006
Posts: 24
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.


---------------------------<br />OCUP-F, SCJP 5.0, SCJD, SCWCD
I agree. Here's the link:
subject: Not using synchronize?!
It's not a secret anymore!