synchronize access to the ExecutorService

This commit is contained in:
Naoyuki Kanezawa
2014-08-17 01:42:52 +09:00
parent bf3bc57244
commit 21fb11f0c2

View File

@@ -4,7 +4,6 @@ package com.github.nkzawa.thread;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory; 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 volatile EventThread thread;
private static AtomicInteger counter = new AtomicInteger(); private static ExecutorService service;
private static int counter = 0;
private EventThread(Runnable runnable) { private EventThread(Runnable runnable) {
super(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. * check if the current thread is EventThread.
* *
@@ -66,16 +58,25 @@ public class EventThread extends Thread {
* @param task * @param task
*/ */
public static void nextTick(final Runnable task) { public static void nextTick(final Runnable task) {
counter.incrementAndGet(); synchronized (EventThread.class) {
getExecutorService().execute(new Runnable() { counter++;
if (service == null || service.isShutdown()) {
service = Executors.newSingleThreadExecutor(THREAD_FACTORY);
}
}
service.execute(new Runnable() {
@Override @Override
public void run() { public void run() {
try { try {
task.run(); task.run();
} finally { } finally {
if (counter.decrementAndGet() == 0) { synchronized (EventThread.class) {
service.shutdown(); counter--;
thread = null; if (counter == 0) {
service.shutdown();
thread = null;
}
} }
} }
} }