Java background server class that might be called from ui thread I have a server communicating over network interface. This server should run on a background thread, so that it does not block the ui thread. The ui thread starts and stops the server. Even starting and stopping should be done from a background thread.

Currently I wrap all public methods of the server class in a thread that gets started immediately:

class Server {

  public void start() {
    new Thread() {
      public void run() {
        handleStart();
      }
    }.start();
  }

  public void stop() {
    new Thread() {
      public void run() {
        handleStop();
      }
    }.start(); 
  }

  private void handleStart() {
    startLooperThread();
  }

  private void handleStop() {
    stopLooperThread();
  }
}


Is this the proper way to do this or are there any neat alternatives provided by JDK (or any other library)?
Disclaimer: This answer uses the lambda-feature for java 8. Assuming non-availability of java 8, the expressions can be easily converted to Runnables.


You're completely overexerting yourself. Use inbuilt features of Java with a little composition and your server becomes by far easier: 

public class Server {
     private final ExecutorService threadPool = Executors.newFixedThreadPool(1);

     public Server() {}

     public void start() {
         threadPool.execute(() -&gt; handleStart()); //Runnable
     }

     public void stop() {
         threadPool.execute(() -&gt; handleStop());
         threadPool.shutdown(); //depends a little on your functionality
     }
     //rest can remain unchanged
}


The Thread-Pool can be expanded manually. Additionally I'd recommend to override finalize() to shut down your executor.