In Groovy code something simple:
#!/usr/bin/env groovy
public class test {
boolean val
def obj=new Object()
def dos() {
val=false
Thread.start() {
synchronized(obj) {
val=true
obj.notifyAll()
}
}
Thread.sleep(5000)
synchronized(obj) {
while (!val) {
obj.wait()
}
}
}
static void main(String[] args) {
def t=new test()
t.dos()
}
}
Ok, here is my problem in more detail.
Thread (A)
start an action in a separate thread, then wait for its completion
— OK THIS IS NOT EXACTLY TRUE OTHERWISE COULD USE thread.join(). This
Thread actually starts a task that then signals methodOne eventually
Thread (B)
we get a signal when action is completed
class A {
private boolean finished
public synchronized void methodOne() {
finished=true;
notifyAll();
}
public void methodTwo() {
new ThreadThatCallsMethodOneWhenDone().start();
synchronized(this) {
while (!finished) {
wait();
}
}
}
}
Is this code okay or am I still running into potential problems? What’s a better way to solve?
Misha
I was wondering, which is correct:
Option One
class A {
public void methodOne() {
synchronized(this) {
modifyvalue
notifyAll()
}
}
public void methodTwo() {
while (valuenotmodified) {
synchronized(this) {
wait()
}
}
}
Option Two
class A {
public void methodOne() {
modifyvalue
synchronized(this) {
notifyAll()
}
}
public void methodTwo() {
while (valuenotmodified) {
synchronized(this) {
wait()
}
}
}
and why?
I think that both are dangerous because your
valuenotmodifiedcheck is performed without synchronisation. So, there is no telling what happens ifmethodOnemodifies the value whilemethodTwois in process of verifying whether it has changed.And I see no difference between your two “options”. Both have this potential problem.