synchronize access to the ExecutorService
This commit is contained in:
@@ -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,19 +58,28 @@ 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) {
|
||||||
|
counter--;
|
||||||
|
if (counter == 0) {
|
||||||
service.shutdown();
|
service.shutdown();
|
||||||
thread = null;
|
thread = null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user