DJ_R
DJ_R

Reputation: 207

Synchronization in Java?

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();

Upvotes: 1

Views: 273

Answers (4)

RichN
RichN

Reputation: 6231

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.

Upvotes: 6

Aaron Digulla
Aaron Digulla

Reputation: 328604

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.

Upvotes: 5

Adamski
Adamski

Reputation: 54705

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.

Upvotes: 1

SoftMemes
SoftMemes

Reputation: 5702

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.

Upvotes: 4

Related Questions