Thread awaiting asynchronous callback

I have Thread

, name it WorkerThread

, whose job it is to make a given object SomeObject

, do some work periodically.

SomeObject

deals with some socket messages. Some of the work it needs to do is done in another thread, dedicated to socket I / O. Name it CommsThread

. I believe that CommsThread

is the internal implementation for SomeObject

.

While SomeObject

busy with his work, the idea is what WorkerThread

will be wait()

on the monitor object. When the asynchronous callback comes from SomeObject

, the callback will be called in the handler notify()

and Thread A

continue on its merry way.

This previously worked, but only because it was Object A

executing its asynchronous callback in context CommsThread

, which means it notify()

can be called on the monitor object, allowing it to WorkerThread

wake up and continue.

I refactor things a bit, and realized that I think it is pretty bad design for my classes to asynchronously call back on a Thread other than the one they were created on, or for these callbacks to happen on the "inner" thread. ... Callbacks were previously executed in context CommsThread

. So in SomeObject

I used Android Handler

to call asynchronous callbacks on the thread it was created on SomeObject

. This is the best design in my opinion. But now it is causing a stalemate in the attitude WorkerThread

. Of course, WorkerThread

now it is in wait()

uncertainty.

This brings me to two related questions:

  • If I'm designing a class or interface that has asynchronous callbacks, is it a convention or just generally a good thing for callbacks to happen either on the thread the object was created on or on the UI thread?

  • Assuming I design my classes as above and the asynchronous callbacks do not happen on a separate thread, how can I WorkerThread

    efficiently wait for such a callback? One way that comes to mind is to create an instance SomeObject

    on the UI thread prior to creation WorkerThread

    and then pass it to the thread. Asynchronous callbacks will execute in the context of the UI thread, so wait()

    / notify()

    will work.

+3


source to share


1 answer


The third solution is to completely abandon the use of the archaic mechanism wait/notify

and use a real parallel structure.

I would suggest that you carefully study your requirements and consider using it BlockingQueue

for inter-thread communication, or perhaps for careful use Lock

.



If you can expand on your actual requirements rather than assume the callback is the correct approach, I'm sure we can help more.

The current relationship with callbacks is that they are almost always scent. However, there are a few patterns that are very similar to callbacks that are considered acceptable.

0


source







All Articles