From 794e24e879539f9cef535577c8593e78a01638a5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9rgio=20Faria?= Date: Thu, 28 Aug 2014 21:42:10 +0100 Subject: [PATCH] The current EventThread doesn't need to be volatile MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Citing the JLS (Java 7) ยง17.4.5: > A call to start() on a thread happens-before any actions in > the started thread. Other threads calling isCurrent(), can see stale values of the static variable, as it doesn't affect the result. Nulling the thread variable, cannot be reordered with the new Thread because a synchronized(EventThread.class) precedes the first task submission on a new Executor, causing a happens-before relationship that ensures the null is already visible to the thread on netTick (that will create the EventThread). --- .../java/com/github/nkzawa/thread/EventThread.java | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/github/nkzawa/thread/EventThread.java b/src/main/java/com/github/nkzawa/thread/EventThread.java index 8921188..5ae896b 100644 --- a/src/main/java/com/github/nkzawa/thread/EventThread.java +++ b/src/main/java/com/github/nkzawa/thread/EventThread.java @@ -15,11 +15,12 @@ public class EventThread extends Thread { @Override public Thread newThread(Runnable runnable) { thread = new EventThread(runnable); + thread.setName("EventThread"); return thread; } }; - private static volatile EventThread thread; + private static EventThread thread; private static ExecutorService service; @@ -58,14 +59,16 @@ public class EventThread extends Thread { * @param task */ public static void nextTick(final Runnable task) { + ExecutorService executor; synchronized (EventThread.class) { counter++; - if (service == null || service.isShutdown()) { + if (service == null) { service = Executors.newSingleThreadExecutor(THREAD_FACTORY); } + executor = service; } - service.execute(new Runnable() { + executor.execute(new Runnable() { @Override public void run() { try { @@ -75,6 +78,7 @@ public class EventThread extends Thread { counter--; if (counter == 0) { service.shutdown(); + service = null; thread = null; } }