Search code examples
javamultithreadingserverfinagle

Best way to run an asynchronous thread in a Finagle Server, on start up


I am getting started with the Finagle library in Java and trying to bring up couple of basic HTTP services which communicate in JSON.
Let this be master and slave services.

Master service has the following logic:

  • It runs a thread on start up which sends command requests to the slave
  • It listens for error/success reports from slave

The slave server's logic is this:

  • For the command it received, it immediately sends an ack.
  • Then it starts a thread to perform a task specified by the command.
  • It sends the result of the job (or error) back to master in JSON.

I have the following code:

HttpMuxer muxService = new HttpMuxer().withHandler("/", new MasterService());
ListeningServer server = Http.serve(new InetSocketAddress("localhost", 8000), muxService);

// This method runs a Function0 closure in a Future pool.
// It sends requests to slave, and exits after the commands are sent.
sendCommands();

try {
    Await.ready(server);
} catch (TimeoutException e) {
    e.printStackTrace();
} catch (InterruptedException e) {
    e.printStackTrace();
}  

My question is this:
Now, ideally the job could take a few seconds to complete. But in case of errors, it could almost immediately send a message to master with error report. Once I call sendCommands(), any moment I can expect the slave to attempt contacting the master.

Is the server up and listening with just the call to Http.serve()? Or does this happen in the Await.ready() call?
I am assuming the latter, and putting a Thread.sleep() in the thread spawned by sendCommands(). Is this required?
Also, is there an altogether better way to cleanly start this command issuing thread at the master?


Solution

  • Okay I figured this out after some testing.

    The call to Http.serve() starts the server on the given port, the incoming requests are correctly handled by the MasterService

    The Await.ready() loop just keeps the thread alive. The server will respond even if you replace this with a Thread.sleep(n)