I have a method which uses CyclicBarrier as shown below:
public void getMessage(Message obj){
CyclicBarrier barrier = new CyclicBarrier(1, new Runnable() {
@Override
public void run() {
synchronized(obj){
System.out.println("--The End --");
}
}
});
executor.execute(new Runnable() {
@Override
public void run() {
synchronized(obj){
//Perform some routine with message object
}
try {
barrier.wait();//java.lang.IllegalMonitorStateException thrown on this line
} catch (InterruptedException e) {
e.printStackTrace();
}
}
开发者_开发知识库 });
}
At the point where i wait for the routine to finish executing, i get:
Exception in thread "pool-2-thread-3"
java.lang.IllegalMonitorStateException
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:502)
Do anyone knows what I am doing wrong here?
In order to call wait()
on any object, the current thread has to own its monitor. You're calling barrier.wait()
without any synchronized(barrier)
.
However, you may have meant to use the await()
method (on CyclicBarrier) instead of wait()
. It's hard to say, as it's not clear what you're trying to achieve.
yeah, you need to gain the monittor of barrier like so:
synchhronized(barrier){
try {
barrier.wait();//java.lang.IllegalMonitorStateException not thrown on this line
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Maybe you did want to use await()
instead that wait()
?
wait
is used to block a thread over a specific object and it is a feature of every object, but in your case you are calling it without taking the monitor of it. You should call wait
from inside the same obect or use a synchronized
block over barrier
itself.
You need to acquire lock before using the barrier object.
Regards, Dheeraj Joshi
The cyclicBarrier is not intended to be used as you do here : participating threads are expected to call the blocking "await()" method.
As a side note, a CyclicBarrier with a count of 1 is totally useless : its intent is to allow a certain number of threads (the barrier count) to wait for each other before continuing. Maybe you should consider changing your whole algorithm, especially if you're not sure about how concurrency stuff works.
精彩评论