aspose file tools*
The moose likes Threads and Synchronization and the fly likes Basic multiple locks in one class question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Basic multiple locks in one class question" Watch "Basic multiple locks in one class question" New topic
Author

Basic multiple locks in one class question

David Pantale
Ranch Hand

Joined: Mar 16, 2010
Posts: 32

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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Basic multiple locks in one class question