Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>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.</p> <p>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):</p> <ul> <li>if you want to take the next message/job when it becomes available from some queue/provider, look at <a href="http://www.javamex.com/tutorials/synchronization_producer_consumer_2.shtml" rel="noreferrer">blocking queues</a></li> <li>if you need to control access to a shared resource with a "lock" on an object, waiting for the lock to become available if necessary, consider plain old synchronized, or an <a href="http://www.javamex.com/tutorials/synchronization_concurrency_9_locks.shtml" rel="noreferrer">explicit lock</a>;</li> <li>if you want to wait for one of many <em>pooled resources</em> to become available, look at <a href="http://www.javamex.com/tutorials/synchronization_concurrency_semaphore.shtml" rel="noreferrer">semaphores</a></li> </ul> <p>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.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload