Created
August 4, 2014 20:50
-
-
Save buchgr/24be953ac1d1b9741dba to your computer and use it in GitHub Desktop.
Pooling of ForkJoinTasks.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.concurrent.Executor; | |
import java.util.concurrent.ForkJoinTask; | |
import java.util.concurrent.RunnableFuture; | |
public class EventLoop implements Runnable { | |
final Executor executor; | |
final AdaptedRunnable pool[] = new AdaptedRunnable[2]; | |
volatile int cnt; | |
EventLoop(Executor executor) { | |
this.executor = executor; | |
// init and call complete so isDone() returns true. | |
pool[0] = new AdaptedRunnable(this); | |
pool[0].complete(null); | |
pool[1] = new AdaptedRunnable(this); | |
pool[1].complete(null); | |
} | |
private Runnable fetchFromPool() { | |
cnt++; | |
AdaptedRunnable next = (AdaptedRunnable) pool[cnt & 1]; | |
for (boolean isDone;;) { | |
isDone = next.isDone(); | |
if (isDone) { | |
break; | |
} | |
} | |
next.reinitialize(); | |
return next; | |
} | |
@Override | |
public void run() { | |
executor.execute(fetchFromPool()); | |
} | |
private static final class AdaptedRunnable extends ForkJoinTask<Void> implements RunnableFuture<Void> { | |
final Runnable runnable; | |
AdaptedRunnable(Runnable runnable) { | |
this.runnable = runnable; | |
} | |
public Void getRawResult() { return null; } | |
public void setRawResult(Void v) { } | |
public boolean exec() { | |
runnable.run(); | |
return true; | |
} | |
public void run() { } | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Arrays; | |
import java.util.concurrent.ForkJoinPool; | |
public class Main { | |
public static void main(String... args) throws InterruptedException { | |
ForkJoinPool fjp = new ForkJoinPool(4); | |
EventLoop loops[] = new EventLoop[4]; | |
for (int i = 0; i < 4; i++) { | |
loops[i] = new EventLoop(fjp); | |
loops[i].run(); | |
} | |
int prevValues[] = new int[4]; | |
Arrays.fill(prevValues, 0); | |
Thread.sleep(100); | |
while (true) { | |
for (int i=0; i < 4; i++) { | |
if (prevValues[i] == loops[i].cnt) { | |
System.out.println("Dead event loop detected: " + loops[i].cnt); | |
return; | |
} else { | |
prevValues[i] = loops[i].cnt; | |
} | |
} | |
Thread.sleep(100); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment