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:
-
How do various standard functions, like the ones above, block? Native code? while() loops? Something else?
-
How should I implement methods that block?
The essential answer to (1) is ‘don’t worry about it — the OS handles it’. Calls to things like reading from input streams are essentially wrappers around operating system calls. Under the hood inside the OS, what I think is usually happening when a call ‘blocks’ in these cases is that the OS ‘knows’ that it is waiting for a hardware interrupt from, say, the disk controller to say that such-and-such requested data is now available, and it knows that Thread X was the one that requested that data. So it doesn’t schedule in Thread X again until it receives that interrupt (or an interrupt saying ‘there was an error’ etc). (And part of the thread scheduling algorithm is then doing things like giving the waiting thread a temporary ‘boost’ of some kind when that waited-for data becomes available. Again, usually you don’t need to worry too much about this.) Or put another way: whatever the exact details of this mechanism, it’s not available to the general Java programmer.
In (2), I would suggest thinking more about ‘how do I do Thing X, which might happen to block’. I think the answer is hardly ever that Thing You Want To Do is deliberately just ‘block’, and whatever Thing X is, there’s probably a library method/class that will do it for you. For example (links include some material I’ve written on these subjects):
I’d say that the raw wait/notify mechanism is largely deprecated with the Java 5 concurrency API. And whatever you’re doing, spinlocking is usually the very very last resort.