Last active
February 20, 2017 22:42
-
-
Save ljnelson/d98f1f357dba7947305602bd2635a814 to your computer and use it in GitHub Desktop.
This file contains 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
private final void startHttpServers(@Observes @Initialized(ApplicationScoped.class) @Priority(LIBRARY_AFTER) final Object event, final BeanManager beanManager) throws IOException, InterruptedException { | |
if (beanManager != null) { | |
final Instance<Object> beans = beanManager.createInstance(); | |
assert beans != null; | |
final Instance<HttpServer> httpServers = beans.select(HttpServer.class); | |
assert httpServers != null; | |
if (!httpServers.isUnsatisfied()) { | |
synchronized (this.startedHttpServers) { | |
for (final HttpServer httpServer : httpServers) { | |
if (httpServer != null) { | |
// This asynchronous method starts a daemon thread in | |
// the background; see | |
// https://github.com/GrizzlyNIO/grizzly-mirror/blob/2.3.x/modules/http-server/src/main/java/org/glassfish/grizzly/http/server/HttpServer.java#L816 | |
// and work backwards to the start() method. Among | |
// other things, that won't prevent the JVM from exiting | |
// normally. Think about that for a while. We'll need | |
// another mechanism to block the CDI container from | |
// simply shutting down. | |
httpServer.start(); | |
// We store our own list of started HttpServers to use | |
// in other methods in this class rather than relying on | |
// Instance<HttpServer> because we don't know what scope | |
// the HttpServer instances in question are. For | |
// example, they might be in Dependent scope, which | |
// would mean every Instance#get() invocation might | |
// create a new one. | |
this.startedHttpServers.add(httpServer); | |
} | |
} | |
if (!this.startedHttpServers.isEmpty()) { | |
// Here we fire an *asynchronous* event that will cause | |
// the thread it is received on to block. This is key: | |
// the JVM will be prevented from exiting, and the thread | |
// that the event is received on is (a) a non-daemon | |
// thread and (b) managed by the container. This is, in | |
// other words, a clever way to take advantage of the CDI | |
// container's mandated thread management behavior so | |
// that the CDI container stays up for at least as long | |
// as the HttpServer we spawned above. | |
// | |
// TODO: fire the event | |
// | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment