1

I have a thread busy-looping until my ServerSocket object binds to a port before doing any read/write operation.

new Thread(() -> {
    while (!server.isBound()) {
        Thread.yield(); // hmm ... any better alternative????
    }
    while (!server.isClosed()) {
        // do stuff regarding server and clients
    }
}, "Server Connection Accept Thread").start();

I've used Thread.yield() in the busy-loop to let other threads run (if there are any) while this thread loops, but the javadoc for Thread.yield() says

It is rarely appropriate to use this method. It may be useful for debugging or testing purposes, where it may help to reproduce bugs due to race conditions.

Now, I don't have a race condition here, I just need to wait until the socket is bound and since there is no callback when the socket gets bound, I'm stuck with this approach. Any advice?

Doga Oruc
  • 783
  • 3
  • 16
  • Can you wait a small amount of time with `Thread.sleep()`? – Progman Sep 08 '20 at 12:35
  • The loop is still very tight and uses a lot of CPU, even though it's just waiting. Does the code really need to respond **immediately** when the socket is bound, or would a few milliseconds delay be ok? Of course a very slight delay is ok, so it would be better to use e.g. `Thread.sleep(100)` to wait 100ms between checks. It's not like you're going to notice a delay like that on startup. – Andreas Sep 08 '20 at 12:36
  • @Progman ```Thread.sleep(10)``` is what I thought instead of ```Thread.yield()``` but since I didn't know if sleeping was better than yielding, I left it as yield. – Doga Oruc Sep 08 '20 at 12:37
  • @Andreas it uses CPU when it's the only Thread to use CPU, the question is, does it still use a lot of CPU when there are other threads doing work? – Doga Oruc Sep 08 '20 at 12:39
  • 1
    It uses all available processing power of one CPU core. If you ran the code on a laptop, you'd curse at the code draining your battery without need. --- Also, it forces the CPU to switch context, and may actually cause enough performance loss to be noticed by other programs that would have liked to use the CPU. Especially if other threads and/or programs used the `yield()` technique too. Since you don't need instant reaction, use a small delay with `sleep`. – Andreas Sep 08 '20 at 12:43
  • 2
    The real question is: Why does the code need an `isBound` loop in the first place? The thread shouldn't have been requested to run the code until after the bind has completed, so the loop should be unnecessary. – Andreas Sep 08 '20 at 12:45
  • @Andreas how can I know when the socket is bound? – Doga Oruc Sep 08 '20 at 12:47
  • 4
    @DogaOruc When `bind()` *returns*. – Andreas Sep 08 '20 at 12:59
  • @Andreas of course! Thank you. – Doga Oruc Sep 08 '20 at 13:09

0 Answers0