I am pretty new to thread-safe programming, and was wondering if I have something like below, would this be safe from deadlock once compiled and run?
public class Foo
{
protected CustomClass[] _mySynchedData = new CustomClass[10];
public void processData()
{
synchron开发者_JS百科ized(_mySynchedData) {
// ...do stuff with synched variable here
}
}
}
public class Bar extends Foo
{
@Override
public void processData()
{
synchronized(_mySynchedData) {
// perform extended functionality on synched variable here
// ...then continue onto parent functionality while keeping synched
super.processData();
}
}
}
Bar testObj = new Bar();
// Deadlock?
testObj.processData();
Your code only display a single thread.
With only one thread, there's no way you can get any deadlock.
Added:
Java language supports what they officially call reentrant synchronization.
It basically means that a single thread can reacquire a lock it already owns.
Your question is what happens when you synchronize two times on the same object.
The answer is: Java will check first which thread owns the monitor (that's the internal data structure on which synchronized
operates). Since the owner thread is the same as the current thread, Java will continue.
Deadlocks can only happen if you have two monitors and you try to lock them in different orders in different threads.
The lock taken by the Java synchronized keyword supports nesting, so you don't risk a deadlock by synchronizing on the same object multiple times in the same thread.
RichN is correct in that your code only contains a single thread and hence deadlock is impossible. Also note that for a deadlock to occur you need to have multiple threads acquiring multiple locks (albeit in a different order) for a deadlock to occur.
Your code currently only references one lock: The one associated with _mySynchedData
. The fact that you attempt to lock it twice does not matter as locks in Java are reentrant.
精彩评论