Monday, June 8, 2015

Behaviour of object refrenced inside synchronized method

Objective here is to show is that any object reference passed to the synchronized method is not locked by the thread executing the synchronized method.


public class DataModel {

    private int Id;
    private String code;

    public DataModel(int id, String code) {
        Id = id;
        this.code = code;
    }

    public synchronized String verbose(LockingThread lockingThread){
        System.out.println(String.format("Is the DataModel object in synchronized block locked by %s ? %s",Thread.currentThread().getName(),Thread.holdsLock(this)));
        return Id+"-______-"+code;
    }
}

Now we have a Thread that will call a synchronized method which has been given reference to DataModel.

public class LockingThread implements Runnable {

    DataModel dataModel;

    public LockingThread() {
        dataModel = new DataModel(1,"model0");
    }

    @Override    public void run() {
        doSomething(dataModel);
    }

    private synchronized void doSomething(DataModel a){
        System.out.println("Is the DataModel object locked ? " + Thread.holdsLock(a));
        System.out.println("Is the Current thread object locked ? " + Thread.holdsLock(this));
//        synchronized (a){            a.verbose(this);
//            System.out.println("Is the DataModel object in synchronized block locked ? " +Thread.holdsLock(a));//        }    }

    public static void main(String[] args){
        LockingThread lockingThread = new LockingThread();
        Thread th = new Thread(lockingThread);
        th.setName("modelThread");
        th.start();
    }

}


This is the actual output :

Is the DataModel object locked ? false
Is the Current thread object locked ? true
Is the DataModel object in synchronized block locked by modelThread ? true  (only when the sync method on datamodel is called)
Is the DataModel object in synchronized block locked ? false (call to sync method of datamodel ended)

No comments:

Post a Comment