The current EventThread doesn't need to be volatile

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).
This commit is contained in:
Sérgio Faria
2014-08-28 21:42:10 +01:00
parent 4741886414
commit 794e24e879

View File

@@ -15,11 +15,12 @@ public class EventThread extends Thread {
@Override @Override
public Thread newThread(Runnable runnable) { public Thread newThread(Runnable runnable) {
thread = new EventThread(runnable); thread = new EventThread(runnable);
thread.setName("EventThread");
return thread; return thread;
} }
}; };
private static volatile EventThread thread; private static EventThread thread;
private static ExecutorService service; private static ExecutorService service;
@@ -58,14 +59,16 @@ public class EventThread extends Thread {
* @param task * @param task
*/ */
public static void nextTick(final Runnable task) { public static void nextTick(final Runnable task) {
ExecutorService executor;
synchronized (EventThread.class) { synchronized (EventThread.class) {
counter++; counter++;
if (service == null || service.isShutdown()) { if (service == null) {
service = Executors.newSingleThreadExecutor(THREAD_FACTORY); service = Executors.newSingleThreadExecutor(THREAD_FACTORY);
} }
executor = service;
} }
service.execute(new Runnable() { executor.execute(new Runnable() {
@Override @Override
public void run() { public void run() {
try { try {
@@ -75,6 +78,7 @@ public class EventThread extends Thread {
counter--; counter--;
if (counter == 0) { if (counter == 0) {
service.shutdown(); service.shutdown();
service = null;
thread = null; thread = null;
} }
} }