sequential event processing via executorservice

你说的曾经没有我的故事 提交于 2019-12-12 01:34:42

问题


I have an event queue to process. A thread adds events to the queue.
I have created a runnable Task that in the run method does all which is necessary to process the event.
I have declared an Executors.newCachedThreadPool(); and I execute each Task.

        public class EventHandler {

            private static final ExecutorService handlers = Executors.newCachedThreadPool();

            public void handleNextEvent(AnEvent event){

                  handlers.execute(new Task(evt)); 

            }   


        public class Task implements Runnable{

        @Override
            public void run() {
            //Event processing
            }
        }

public AnotherClass{    
    public void passEvent(AnEvent evt)//This is called by another thread
    {
      EventHandler.handleNextEvent(evt);

    }
}

My problem is that if I call execute of the executor, my code will get the next event and run next runnable via the executor. My purpose is to process next event from queue only after previous task has ended.
How would I know that the previous task has finished or not so that I know I can call handleNextEvent again?
Is having some status field updated by the Task a good idea?

Thanks


回答1:


Executors.newCachedThreadPool() will create new threads on demand, so it's not what you want. You want something like Executors.newSingleThreadExecutor(), which will process the events one at a time, and queue up the rest.

See javadoc:

Creates an Executor that uses a single worker thread operating off an unbounded queue. (Note however that if this single thread terminates due to a failure during execution prior to shutdown, a new one will take its place if needed to execute subsequent tasks.) Tasks are guaranteed to execute sequentially, and no more than one task will be active at any given time.




回答2:


I think Executors.newSingleThreadExecutor() and the submit() Method are the solution to your problem: http://download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/ExecutorService.html



来源:https://stackoverflow.com/questions/4104420/sequential-event-processing-via-executorservice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!