Re: How to acquire object's monitor optionally?
Chris wrote:
If I have the spun-off thread do the locking and unlocking, then I get a
problem where the main thread spins off the thread, a condition changes
and I no longer want to execute the method (basically the app needs to
shutdown), then the spun off thread tries to lock and I get errors. I
really need to have the main thread attempt to lock before it spins off
the other thread.
If you get errors, you should handle them. If the errors likely
indicate that a shutdown is imminent, you should probably just have the
thread exit.
You might also implement an interrupt policy for your threads.
Interrupt = exit. Then you can just interrupt any still running threads
to have them shutdown.
The answer, perhaps, is to have the spun-off thread check to see if
we're in shutdown mode before it runs. But I get errors there, too --
I've got to create a "shutting-down" flag, and have a synchronized {}
around that, and for some reason things aren't happening in the right
sequence.
You sound like you have a lot of race conditions. Time to back up and
think about this more strategically. What if you need to shutdown just
after the thread has checked the "shutting-down flag?"
I think you need a different way of handling the shutdown case,
something much more organic to Java and the problem. Constantly
checking flags isn't going to help. Shutdown for you sounds like a 100%
asynchronous event.
(You can poll a flag inside a thread to test for done, but it's tricky
and error prone. You sound like you're still struggling over some of
the basics of Java concurrency. Correct me if I'm wrong about that.)
If I could have a ReentrantLock where the locking and unlocking threads
were different, then I think things would work ok.
I sort of doubt that.
Any chance we could get a small SSCCE that demonstrates the problem?
Also, if you don't have Java Concurrency in Practice, you need to order
it pronto.