• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

ReentrantLock

 
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
author
Posts: 23951
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks a lot for your explanation!

Stefan
reply
    Bookmark Topic Watch Topic
  • New Topic