Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Basic multiple locks in one class question

 
David Pantale
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Am I correct in assuming that a lock behaves similarly to synchronized code in the following way - If I have the following class below:

Class X {
private ReentrantLock lock = new ReentrantLock();

public increment() {
lock.lock();
try {

// some stuff
} finally {
lock.unlock();
}

public decrement() {
lock.lock();
try {

// and some other stuff
} finally {
lock.unlock();
}
}

public otherMethod() {
try {
// more other stuff but no lock
}
}

}

Then if thread #1 start to execute the increment method, then thread #2 cannot begin executing the decrement method but can execute the otherMethod because the lock code executed in the increment method also stops thread #2 from executing decrement?

Thanks
Dave
 
Angel Taveras
Ranch Hand
Posts: 84
Eclipse IDE Hibernate Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello David, you're right the ReentrantLock it's the same as the synchronized keyword. With the reentrantlock you can do somethings that with the synchronized you cannot like the posibility to take the lock in a method and release the lock in other method with the synchonized it's automatically taken and released when the scope start/ends.

Regards,

Angel
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic