Why does this code result in illegalMonitorState exception?

前端 未结 2 1808
情歌与酒
情歌与酒 2020-12-20 03:29

The code below is trying to insert a random value into a circular queue and remove it. However, there are some synchronization issues. I know I can use higher level routines

相关标签:
2条回答
  • 2020-12-20 03:53

    another problem in this code is that even if isEmpty/isFull return true - until you call the adjacent wait the state of the queue might change.
    For example:
    - queue is empty
    - thread 1 calls isEmpty()
    - context switch
    - thread 2 calls enqueue (now the queue is not empty)
    - context switch
    - thread 1 not calls lock.wait() event though the queue is not empty

    this problem of course will be solved when calls to wait()/notify() will be placed in a synchronized block.

    0 讨论(0)
  • 2020-12-20 03:59

    Because java.lang.Object#wait, java.lang.Object#notify, java.lang.Object#notifyAll must be called from synchronized block.

    As a solution(need to check) you should put your conditions inside synchronized blocks:

    void enqueue(int number) throws InterruptedException
    {
    
        synchronized(lock)
        {
            if(isFull())
               lock.wait();
    
            array[rear] = number;
            System.out.println("Rear is:"+ rear+ "value is:"+number+"Size is:"+size);
    
            rear = (rear+1)%size;
            count++;
            lock.notify();
        }
    }
    
    void dequeue() throws InterruptedException
    {
        synchronized(lock)
        {
            if(isEmpty())
               lock.wait();
    
            int retVal = 0;
            retVal = array[front];
            System.out.println("Front is:"+ front+ "value is:"+retVal);
    
            front = (front+1)%size;
            count--;
            lock.notify();
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题