开发者

How to ensure a java code section has the monitor

So I'm writing an introductory java program to get used to multithreading, however, I'm having a little bit of trouble with the monitors. In particular, the below code section is throwing an IllegalMonitorStateException when I make the primes[0].notifyAll() call.开发者_开发问答

    Integer[] primes=new Integer[3];
    if(primes[0]>0{
        {
        synchronized(primes[0]){
           int returning=primes[0];
           primes[0]=0;
           primes[0].notifyAll();
           return returning;}
     }

My understanding of the synchronized keyword was that it ensured that you had the monitor before entering the code block, so by that logic I should have the monitor for the notifyAll() call. Am I misunderstanding the strategy that Java uses for synchronizing or is there some bug in the way I'm implementing that?


The problem is that you have reassigned a new object to primes[0].

synchronized(primes[0])

The above statement has synchronized on the object referenced by primes[0]

primes[0]=0;

The above statement has now reassigned a new object to primes[0], NOT the one you own a lock/monitor on.

primes[0].notifyAll();

Lastly you're trying to notifyAll() on the new object, not the one you have a lock on, hence the exception.

Depending upon what you're trying to accomplish, the following may do what you want:

Integer[] primes=new Integer[3];
if(primes[0]>0) {
  synchronized(primes[0]) {
    int returning=primes[0];
    primes[0]=0;
    returning.notifyAll();
    return returning;
  }
}


Integer[] primes=new Integer[3];
if(primes[0]>0{

i would expect you get null pointer exceptions here, as primes[0] hasn't been allocated.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜