javasynchronizationsynchronizedsynchronize

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

Solution

  • 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.