kamal
kamal

Reputation: 105

Thread loses lock and gives another thread a chance to execute

Here I have an object with 2 threads and providing lock on object by print() but after some loop it losing lock and execute the second thread and it will change the value of breakLoop and first thread will be terminate.

public class ThreadLock {
    public static void main(String[] args) {
        Entity entity=new Entity();
        RunnableClass runnable = new RunnableClass(entity);
        Thread threadClass= new Thread(runnable);
        Thread threadClass2= new Thread(runnable);
        threadClass.setName("First Thread");
        threadClass2.setName("Second Thread");
        threadClass.start();        
        threadClass2.start();
    }
}

class RunnableClass implements Runnable{
    Entity entity;
    public RunnableClass(Entity entity) {
        this.entity=entity;
    }
    public void run(){
        if(Thread.currentThread().getName().equalsIgnoreCase("First Thread"))
            entity.print();
        else{
            entity.print("");
        }
    }
}
class Entity{
    public void print(String str){
        System.out.println("Non sysncronized method accessed by  "+Thread.currentThread().getName());
        breakLoop=false;
    }
    boolean breakLoop=true;
    //lock will work for same object 
    public synchronized void print(){
        System.out.println("Lock aquired by : "+Thread.currentThread().getName());
        while (breakLoop) {
            System.out.println("hhhhhhhhhhhhhh");
        }
        System.out.println("Lock released by : "+Thread.currentThread().getName());
    }
}

Upvotes: 0

Views: 66

Answers (1)

Nathan Hughes
Nathan Hughes

Reputation: 96434

The first thread having the lock doesn't stop the second thread from calling the Entity.print(String) method, because that method doesn't try to acquire the lock. Calling print(String) sets the breakLoop flag to false.

(When the flag value becomes visible to the other thread is not well-defined due to memory visibility issues --it would be better to make the breakLoop instance variable volatile-- but that doesn't necessarily mean the second thread will never see the change to the instance variable. Memory visibility issues are more apparent on some platforms than others.)

If you change the print(String) method to be synchronized, it will hang waiting for the first thread to finish.

Upvotes: 2

Related Questions