0

I have a thread A which runs another thread B. Thread A implements a method "stopExec()" which tries to exit thread B cleanly - allowing it to finish some tasks. So my stopExec method looks something like this:

private CountDownLatch lock;

public void stopExec() {
  lock = new CountDownLatch(1);
  threadB.finish();
  try {
    lock.await();
  } catch(InterruptedExcetion ie) {
    Log.d(null, "Thread A not locked.");
  }
  Log.d(null, "Finished.");
}

Thread B has a reference to Thread A and it calls "threadA.lock.countDown();" when it finished whatever it was doing.

What happenes it that exception is thrown...thread A doesn't wait, but simply continues. Can somebody explain me why/what am I doing wrong. I have used CountDownLatch in a similar way in other cases and it is working as expected.

Thank you!

Andremoniy
  • 34,031
  • 20
  • 135
  • 241
hpet
  • 299
  • 2
  • 14

1 Answers1

0
lock = new CountDownLatch(1);
threadB.finish();

This code is broken: it contains a data race on the lock variable. Try resolving your issue by making the lock variable volatile.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436