Two Laptop Bag*
The moose likes Threads and Synchronization and the fly likes ReentrantLock Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "ReentrantLock" Watch "ReentrantLock" New topic
Author

ReentrantLock

Stefan Krompass
Ranch Hand

Joined: Apr 29, 2004
Posts: 75
Hi,

I read in the Javadoc for JDK 5.0 that we can "simulate" synchronized methods with the java.util.concurrent.locks.ReentrantLock-class. Consider we have something like this:

When a thread executes the code of method foo, another thread can execute the code of method bar at "the same time".
But how do I replace the synchronized keyword? At first, I considered implementing a single lock using java.util.concurrent.locks.ReentrantLock:

But with this solution it is no longer possible that a thread executes foo() while another thread executes bar() since only one thread can hold the lock.
Does that mean that we need to introduce a variable of class java.util.concurrent.locks.ReentrantLock for every method we want to synchronize?

Or did I understand something wrong?

Stefan
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18846
    
  40

When a thread executes the code of method foo, another thread can execute the code of method bar at "the same time".


No... if both foo() and bar() are synchronized, they can't run at "the same time" by different threads.

But with this solution it is no longer possible that a thread executes foo() while another thread executes bar() since only one thread can hold the lock.


True... which is exactly the same functionality as using the synchronized keyword.

And BTW, I would recommend coding like this:



With the way you had it coded, the lock will remain held, if an exception is thrown.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Stefan Krompass
Ranch Hand

Joined: Apr 29, 2004
Posts: 75
Thanks a lot for your explanation!

Stefan
 
 
subject: ReentrantLock