33

An example taken from an Embedded Jetty tutorial suggests the following:

public static void main(String[] args) throws Exception
{
   Server server = new Server(8080);
   server.setHandler(new HelloHandler());

   server.start();
   server.join();}

Why do I need to add the line server.join()? It works fine without it.

Brad Koch
  • 19,267
  • 19
  • 110
  • 137
Loner shushman
  • 757
  • 3
  • 8
  • 18

1 Answers1

-8

join() is blocking until server is ready. It behaves like Thread.join() and indeed calls join() of Jetty's thread pool. Everything works without this because jetty starts very quickly. However if your application is heavy enough the start might take some time. Call of join() guarantees that after it the server is indeed ready.

AlexR
  • 114,158
  • 16
  • 130
  • 208
  • It is not really that quick,it took 1/3 of a minute to load a server, still dont see how join will help me. – Loner shushman Apr 10 '13 at 13:04
  • 26
    `Server.join()` waits for the server to fully stop, without it the example in the question would start and the `main()` would exit causing the JVM to shutdown. – Joakim Erdfelt Apr 10 '13 at 13:13
  • 7
    `Server.start()` will return once the main lifecycle of the server has completed it startup. Which includes all of the components you specify and attach to the Server before the call to `Server.start()`. Note however that some components, such as the DeploymentManager (which the question does not use) have their own thread which is not beholden to this generalization. It is good practice, for example, to ask the Connectors for their state after `Server.start()` and before `Server.join()` – Joakim Erdfelt Apr 10 '13 at 13:16
  • 1
    Should I care that the JVM is not shut down but the main() exit.? The main exit, that is fine but the server is still running in the background, which is what I want – Loner shushman Apr 10 '13 at 13:48
  • 10
    Why is this upvoted (and accepted) when clearly the answer is wrong? Like @JoakimErdfelt said, join() waits for the server (thread) to stop and not until the server has fully started. – helpermethod Oct 20 '15 at 10:36
  • 1
    @helpermethod the call to `Server.start()` waits for the server to fully start. It follows the Component LifeCycle behavior of Jetty. Components that spawn threads and behave outside of the LifeCycle are excluded from this statement (like the FileSystem change Scanner and DeploymentManager) – Joakim Erdfelt Oct 20 '15 at 12:54
  • 6
    I removed the join and everything works as usual. The server's threadpool contains non daemon threads, which means that the server stays alive even when the main finishes. So...why join? – AlikElzin-kilaka Mar 07 '16 at 18:51