views:

132

answers:

4

Hi,

Quick question. 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()
    {
        synchronized(_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();

Any insight would be greatly appreciated.

+5  A: 

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.

RichN
Actually, if it _didn't_ support nesting (and not all locks do), I'd very well call it a deadlock, even though there would be only one thread involved.
Freed
Thanks for the info and link!
DJ_R
+4  A: 

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.

Freed
+1  A: 

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.

Adamski
+3  A: 

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.

Aaron Digulla