开发者

ScheduledExecutorService reuse

So, let's say I have the following ScheduledExecutorService:

public class Foo
{
        private ScheduledExecutorService exec;

        public Foo()
        {
            exec = Executors.newScheduledThreadPool(NUM_OF_TASKS);
        }

        public void executeOnce()
        {
            exec.schedule(new Runnable(){
                @Override
                public void run()
                {
                    Foo.this.doSomething();
                }}, DELAY, TimeUnit.MILLISECONDS);
        }
}

Now, exec is used to execute periodic tasks (e.g. directory polling, and etc). But, there's this one task (i.e. executeOnce) that is executed once, but requires a delay. So, I chose to use exec to execute this task, but is this good design? Instead, should I have created a newSingleThreadExe开发者_开发技巧cutor, and then subsequently called shutdown? For instance,

public void executeOnce()
{
    // Execute task and wait 'til completion      
    ExecutorService exec = Executors.newSingleThreadExecutor();
    try {
        exec.submit(new Runnable(){
            @Override
            public void run() 
            {   
                try 
                {
                    Thread.sleep(DELAY);
                } catch (InterruptedException e) {
                }
                Foo.this.doSomething()
            }   
        }).get();
    } catch (InterruptedException e) {
    } catch (ExecutionException e) {
    }

    // Shutdown executor service    
    exec.shutdownNow();        
 }

Are there any benefits implementing the latter?


If the regular tasks and the one-time task are related in some way and the scheduling of the regular tasks is not as critical that a (possible) delay in their execution is a problem, then I'd simply execute the one-time task on the same executor.

The advantage of using a separate executor would be that the regular tasks are scheduled without interference. However shutdownNow() would almost certainly not have the desired effect here, a simple shutdown() would be more appropriate.


If exec is reused for other tasks, the initial piece strikes me as more elegant. Creation of a thread is a non-trivial task, even the runnable is only being executed once, the general approach to threading is to creaate a single thread pool and throw runnables at them. Makes life easier, centralizes thread pools, etc...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜