public abstract boolean isBlocking(); public abstract Object blockingLock();

public abstract boolean isBlocking(); public abstract Object blockingLock(); } Readiness selection is a mechanism by which a channel can be queried to determine if it’s ready to perform an operation of interest, such as reading or writing. Nonblocking I/O and selectability are intimately linked. That’s why the API methods for managing blocking mode are defined in the SelectableChannel superclass. The remainder of SelectableChannel’s API will be discussed in Chapter 4. Setting or resetting a channel’s blocking mode is easy. Simply call configureBlocking() with true to place it in blocking mode, or false for nonblocking mode. It’s as simple as that. You can determine which mode a socket channel is currently in by invoking isBlocking(): SocketChannel sc = SocketChannel.open(); sc.configureBlocking (false); // nonblocking … if ( ! sc.isBlocking()) { doSomething (cs); } Nonblocking sockets are usually thought of for server-side use because they make it easier to manage many sockets simultaneously. But there can also be benefits to using one or a few sockets in nonblocking mode on the client side. For example, with nonblocking sockets, a GUI application can pay attention to user requests and carry on conversations with one or more servers simultaneously. Nonblocking mode is useful across a broad range of applications. Occasionally, it’s necessary to prevent changes to the blocking mode of a socket channel. The API provides the blockingLock() method, which returns an opaque object reference. The object returned is the one used internally by the channel implementation when it makes changes to the blocking mode. Only the thread holding the lock on this object will be able to change the channel’s blocking mode. (An object lock is obtained by using the synchronized Java keyword. This is different than the lock() method discussed in Section 3.3.) This can be handy to ensure that the blocking mode of a socket doesn’t change during a critical section of code, or to change the mode temporarily without affecting any other threads. Socket socket = null; Object lockObj = serverChannel.blockingLock(); // have a handle to the lock object, but haven’t locked it yet // may block here until lock is acquired synchronize (lockObj) { // This thread now owns the lock; mode can’t be changed boolean prevState = serverChannel.isBlocking(); 104

Hint: This post is supported by Gama web hosting hrvatska services

Comments are closed.