Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Block without spinning in Java?

Certain methods in Java will block until they can do something, like ServerSocket.accept() and InputStream.read(), but how it does this is not easy for me to find. The closest thing I can think of is a while() loop with a Thread.sleep() each time through, but the longer the sleep period, the less responsive the blocking, and the shorter the sleep, the more spinning that occurs.

I have two questions:

  1. How do various standard functions, like the ones above, block? Native code? while() loops? Something else?

  2. How should I implement methods that block?

like image 572
Nate Parsons Avatar asked Nov 29 '22 07:11

Nate Parsons


1 Answers

The operations you've listed block because of the underlying platform (ie. native code).

You can implement a block using Java's Object.wait() and Object.notify() methods; wait() will block the calling thread until another thread calls notify() on the same lock.

like image 186
MandyK Avatar answered Dec 05 '22 10:12

MandyK