From 21fb11f0c2bfe04d2bdbb4567a6cfb44ade633fe Mon Sep 17 00:00:00 2001 From: Naoyuki Kanezawa Date: Sun, 17 Aug 2014 01:42:52 +0900 Subject: [PATCH] synchronize access to the ExecutorService --- .../com/github/nkzawa/thread/EventThread.java | 33 ++++++++++--------- 1 file changed, 17 insertions(+), 16 deletions(-) diff --git a/src/main/java/com/github/nkzawa/thread/EventThread.java b/src/main/java/com/github/nkzawa/thread/EventThread.java index 8173f9d..8921188 100644 --- a/src/main/java/com/github/nkzawa/thread/EventThread.java +++ b/src/main/java/com/github/nkzawa/thread/EventThread.java @@ -4,7 +4,6 @@ package com.github.nkzawa.thread; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; -import java.util.concurrent.atomic.AtomicInteger; /** @@ -20,24 +19,17 @@ public class EventThread extends Thread { } }; - private static ExecutorService service; - private static volatile EventThread thread; - private static AtomicInteger counter = new AtomicInteger(); + private static ExecutorService service; + + private static int counter = 0; private EventThread(Runnable runnable) { super(runnable); } - private static ExecutorService getExecutorService() { - if (service == null || service.isShutdown()) { - service = Executors.newSingleThreadExecutor(THREAD_FACTORY); - } - return service; - } - /** * check if the current thread is EventThread. * @@ -66,16 +58,25 @@ public class EventThread extends Thread { * @param task */ public static void nextTick(final Runnable task) { - counter.incrementAndGet(); - getExecutorService().execute(new Runnable() { + synchronized (EventThread.class) { + counter++; + if (service == null || service.isShutdown()) { + service = Executors.newSingleThreadExecutor(THREAD_FACTORY); + } + } + + service.execute(new Runnable() { @Override public void run() { try { task.run(); } finally { - if (counter.decrementAndGet() == 0) { - service.shutdown(); - thread = null; + synchronized (EventThread.class) { + counter--; + if (counter == 0) { + service.shutdown(); + thread = null; + } } } }