Calling sleep in a cycle usually results in poor performance. For example:
while (true) { if (stream.available() > 0) { // read input } sleep(MILLISECONDS); }
If MILLISECONDS is too large, then this code will take a long time to understand that the input is available.
If MILLISECONDS is too small, then this code will spend a lot of system resources on input that has not arrived yet.
Other uses of sleep in a loop are usually also dubious. Generally, the best way.
If this is a problem, what should I do instead?
Send the code and maybe we can give you a reasonable answer.
EDIT
IMO, the best way to solve the problem is to use ThreadPoolExecutor .
Something like that:
public void listen() { BlockingQueue queue = new SynchronousQueue(); ThreadPoolExecutor executor = new ThreadPoolExecutor( 1, Session.getMaxSessionCount(), 100, TimeUnit.SECONDS, queue); while (true) { try { queue.submit(new Session(database, serverSocket.accept())); } catch (IOException ex) { ex.printStackTrace(); } } }
This sets up the executor as your code works. There are many other ways to do this; see javadoc link above.
Stephen C Aug 21 2018-10-18T00: 00Z
source share