Skip to content

Instantly share code, notes, and snippets.

@jnorthrup
Created July 14, 2014 20:56
Show Gist options
  • Save jnorthrup/c625fa772766996c2cfe to your computer and use it in GitHub Desktop.
Save jnorthrup/c625fa772766996c2cfe to your computer and use it in GitHub Desktop.
/**
* handles SslEngine state NEED_TASK.creates a phaser and launches all threads with invokeAll
*
* @param key
* @param sslEngine
* @param executorService
* @return
*/
public static int delegateTasks(final SelectionKey key, SSLEngine sslEngine, ExecutorService executorService) {
final int origOps = key.interestOps();
List<Callable<Void>> runnables = new ArrayList<>();
final AtomicReference<Phaser> phaser = new AtomicReference<>( );
Runnable t;
while (null != (t = sslEngine.getDelegatedTask())) {
final Runnable finalT1 = t;
runnables.add(new Callable<Void>() {
@Override
public Void call() throws Exception {
finalT1.run();
phaser.get().arriveAndAwaitAdvance();
return null;
}
});
}
runnables.add(new Callable<Void>() {
@Override
public Void call() throws Exception {
;
Phaser phaser1 = phaser.get();
phaser1.awaitAdvanceInterruptibly(phaser1.arrive());
key.interestOps(origOps);
return null;
}
});
try {
key.interestOps(0);
phaser.set(new Phaser(runnables.size() ));
executorService.invokeAll(runnables);
} catch (InterruptedException e) {
e.printStackTrace();
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment