| Author |
Basic multiple locks in one class question
|
David Pantale
Ranch Hand
Joined: Mar 16, 2010
Posts: 31
|
|
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
Joined: Nov 13, 2008
Posts: 84
|
|
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
|
 |
 |
|
|
subject: Basic multiple locks in one class question
|
|
|