[Logo]
Forums Register Login
ReentrantLock
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
 

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
Thanks a lot for your explanation!

Stefan
You can't expect to wield supreme executive power just because
ScroogeXHTML 7.1 - RTF to HTML5 / XHTML converter
https://coderanch.com/t/690611/ScroogeXHTML-RTF-HTML-XHTML-converter


This thread has been viewed 909 times.

All times above are in ranch (not your local) time.
The current ranch time is
Feb 20, 2018 03:07:16.