Search code examples
javamultithreadingeventsqueuethread-local

A queue per thread implementation


How would you implement a Listener that is queuing events that are executed at the end of thread execution in multithreading environment? The desired behavior would be that each thread has its own queue for events so that they wouldn't mix up and be atomically executed.. So that if thread A calls listener.execute() then only "his" events get executed.

The only way I can think of is using ThreadLocal variable but if I consider the complications here I'd rather not use any.

Let say you have a Tree and you want to remove x nodes, then you don't want to execute refresh x times after each "refresh" event, but you better want to queue them and execute at the end...that spares x-1 refreshes :-)


Solution

  • If you really want to avoid ThreadLocal, you could inverse the pattern and store a weak reference of the owner thread with every event in your (unique) queue.

    This would also allow the redeploying to any other thread if the owner isn't available anymore.

    But I'm a little unsure as I never saw the need for such a queue of events executed at "end of thread execution". Do you really have threads or are they really tasks or runnables ?