Question

Why the following very simple code does not work.. it gets stuck.. I am trying to use the explicit lock java.util.concurrent.locks.ReentrantLock; and its newCondition() method.

Here is my code:

    import java.util.concurrent.locks.Condition;
    import java.util.concurrent.locks.ReentrantLock;

    public class TheCondition implements Runnable {

        ReentrantLock lock = new ReentrantLock();
        Condition condition = lock.newCondition();

        static int variable = 2;

        public void incrementVariable() throws InterruptedException
        {
            lock.lock();
            try{    
               condition.await();
               for (int i = 0;i<100000;i++){
                         variable++;
               }
            }   
            finally
            {
               lock.unlock();
            }
        }


        public static void main (String []args) throws InterruptedException
        {
            TheCondition tc = new TheCondition();
            Thread t1 = new Thread(tc);
            t1.start();
            Thread.sleep(1000);
            tc.incrementVariable();
            t1.join();
            System.out.println(variable);
        }

        public void run()
        {
            for (int i = 0;i<100000;i++){
                variable++;     
            }
            System.out.println(variable);
            lock.lock();
            try{
                condition.signalAll();
            }
            finally{
                lock.unlock();
            }
        }
    }

I am locking on the same lock so it should be working... instead it gets blocked in the main thread when it calls incrementVariable(). Why would it happen such a thing? Thanks in advance.

Was it helpful?

Solution

You first execute run, which completes in a few microseconds. This method calls signalAll at the time when no threads are awaiting the signal. Then, after one second, you call incrementVariable in the main thread, which, naturally, hangs on the await method, never receiving a signal.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top