not request the same locks in the same

not request the same locks in the same order, there is a potential for deadlock. If you are certain that no other threads will be accessing the selector at the same time, then synchronization is not necessary. The close() method of Selector synchronizes in the same way as select(), so there is a potential for blocking there. A thread calling close() will block until an in-progress selection is complete or the thread doing the selection goes to sleep. In the latter case, the selecting thread will awaken as soon as the closing thread acquires the locks and closes the selector (see Section 4.3.2). 4.4 Asynchronous Closability It’s possible to close a channel or cancel a selection key at any time. Unless you take steps to synchronize, the states of the keys and associated channels could change unexpectedly. The presence of a key in a particular key set does not guarantee that the key is still valid or that its associated channel is still open. Closing channels should not be a time-consuming operation. The designers of NIO specifically wanted to prevent the possibility of a thread closing a channel being blocked in an indefinite wait if the channel is involved in a select operation. When a channel is closed, its associated keys are cancelled. This does not directly affect an in-process select(), but it does mean that a selection key that was valid when you called select() could be invalid upon return. You should always use the selected key set returned by the selector’s selectedKeys() method; do not maintain your own set of keys. Understanding the selection process as outlined in Section 4.3.1 is important to avoid running into trouble. Refer to Section 4.3.2 for the details of how a thread can be awakened when blocked in select(). If you attempt to use a key that’s been invalidated, a CancelledKeyException will be thrown by most methods. You can, however, safely retrieve the channel handle from a cancelled key. If the channel has also been closed, attempting to use it will yield a ClosedChannelException in most cases. 4.5 Selection Scaling I’ve mentioned several times that selectors make it easy for a single thread to multiplex large numbers of selectable channels. Using one thread to service all the channels reduces complexity and can potentially boost performance by eliminating the overhead of managing many threads. But is it a good idea to use just one thread to service all selectable channels? As always, it depends. It could be argued that on a single CPU system it’s a good idea because only one thread can be running at a time anyway. By eliminating the overhead of context switching between threads, total throughput could be higher. But what about a multi-CPU system? 152
Note: If you are looking for best hosting provider to host and run your tomcat application check Astra tomcat hosting services

Comments are closed.