In the application from the main method in a separate thread, I launch the websocket server:

try { server.start(); while(true){} } catch (DeploymentException e) { e.printStackTrace(); } finally { server.stop(); } 

In order for the server to "endlessly" wait for new connections, you need to prevent this thread from ending after the server starts. So far, just put an infinite while loop for this, but it is very processor-intensive. What could be the way to pause the method?

1 answer 1

The best option is not to do an extra flow where it is not needed. If the server worked in the specified stream and did not create a new one, then it would be less of a problem :)

Or, alternatively, it is necessary to note the stream in which the server listens to connections, the main one ( .setDaemon(false) ) - and simply remove the server.stop() call, because the queue will never reach it.

As for your task, any method of falling asleep forever or for a long time will suit you:

  • Thread.sleep(дофига) in a loop
  • Lock lock = new ReentrantLock(); lock.lock(); lock.newCondition().await();
  • simple Object obj = new Object(); synchronized (obj) obj.wait(); Object obj = new Object(); synchronized (obj) obj.wait();

If you also need to provide a stop mechanism, then the easiest way - System.console().readLine() instead of a cycle - will stop the server by pressing Enter.