Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

ReentrantLock

 
Stefan Krompass
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Marshal
Pie
Posts: 21412
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Stefan Krompass
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot for your explanation!

Stefan
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic