1. /*
  2. * @(#)Selector.java 1.37 04/05/05
  3. *
  4. * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
  5. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  6. */
  7. package java.nio.channels;
  8. import java.io.IOException;
  9. import java.nio.channels.spi.SelectorProvider;
  10. import java.util.Set;
  11. /**
  12. * A multiplexor of {@link SelectableChannel} objects.
  13. *
  14. * <p> A selector may be created by invoking the {@link #open open} method of
  15. * this class, which will use the system's default {@link
  16. * java.nio.channels.spi.SelectorProvider </code>selector provider<code>} to
  17. * create a new selector. A selector may also be created by invoking the
  18. * {@link java.nio.channels.spi.SelectorProvider#openSelector openSelector}
  19. * method of a custom selector provider. A selector remains open until it is
  20. * closed via its {@link #close close} method.
  21. *
  22. * <a name="ks">
  23. *
  24. * <p> A selectable channel's registration with a selector is represented by a
  25. * {@link SelectionKey} object. A selector maintains three sets of selection
  26. * keys:
  27. *
  28. * <ul>
  29. *
  30. * <li><p> The <i>key set</i> contains the keys representing the current
  31. * channel registrations of this selector. This set is returned by the
  32. * {@link #keys() keys} method. </p></li>
  33. *
  34. * <li><p> The <i>selected-key set</i> is the set of keys such that each
  35. * key's channel was detected to be ready for at least one of the operations
  36. * identified in the key's interest set during a prior selection operation.
  37. * This set is returned by the {@link #selectedKeys() selectedKeys} method.
  38. * The selected-key set is always a subset of the key set. </p></li>
  39. *
  40. * <li><p> The <i>cancelled-key</i> set is the set of keys that have been
  41. * cancelled but whose channels have not yet been deregistered. This set is
  42. * not directly accessible. The cancelled-key set is always a subset of the
  43. * key set. </p></li>
  44. *
  45. * </ul>
  46. *
  47. * <p> All three sets are empty in a newly-created selector.
  48. *
  49. * <p> A key is added to a selector's key set as a side effect of registering a
  50. * channel via the channel's {@link SelectableChannel#register(Selector,int)
  51. * register} method. Cancelled keys are removed from the key set during
  52. * selection operations. The key set itself is not directly modifiable.
  53. *
  54. * <p> A key is added to its selector's cancelled-key set when it is cancelled,
  55. * whether by closing its channel or by invoking its {@link SelectionKey#cancel
  56. * cancel} method. Cancelling a key will cause its channel to be deregistered
  57. * during the next selection operation, at which time the key will removed from
  58. * all of the selector's key sets.
  59. *
  60. * <a name="sks"><p> Keys are added to the selected-key set by selection
  61. * operations. A key may be removed directly from the selected-key set by
  62. * invoking the set's {@link java.util.Set#remove(java.lang.Object) remove}
  63. * method or by invoking the {@link java.util.Iterator#remove() remove} method
  64. * of an {@link java.util.Iterator </code>iterator<code>} obtained from the
  65. * set. Keys are never removed from the selected-key set in any other way;
  66. * they are not, in particular, removed as a side effect of selection
  67. * operations. Keys may not be added directly to the selected-key set. </p>
  68. *
  69. *
  70. * <a name="selop">
  71. * <h4>Selection</h4>
  72. *
  73. * <p> During each selection operation, keys may be added to and removed from a
  74. * selector's selected-key set and may be removed from its key and
  75. * cancelled-key sets. Selection is performed by the {@link #select()}, {@link
  76. * #select(long)}, and {@link #selectNow()} methods, and involves three steps:
  77. * </p>
  78. *
  79. * <ol>
  80. *
  81. * <li><p> Each key in the cancelled-key set is removed from each key set of
  82. * which it is a member, and its channel is deregistered. This step leaves
  83. * the cancelled-key set empty. </p></li>
  84. *
  85. * <li><p> The underlying operating system is queried for an update as to the
  86. * readiness of each remaining channel to perform any of the operations
  87. * identified by its key's interest set as of the moment that the selection
  88. * operation began. For a channel that is ready for at least one such
  89. * operation, one of the following two actions is performed: </p>
  90. *
  91. * <ol type=a>
  92. *
  93. * <li><p> If the channel's key is not already in the selected-key set then
  94. * it is added to that set and its ready-operation set is modified to
  95. * identify exactly those operations for which the channel is now reported
  96. * to be ready. Any readiness information previously recorded in the ready
  97. * set is discarded. </p></li>
  98. *
  99. * <li><p> Otherwise the channel's key is already in the selected-key set,
  100. * so its ready-operation set is modified to identify any new operations
  101. * for which the channel is reported to be ready. Any readiness
  102. * information previously recorded in the ready set is preserved; in other
  103. * words, the ready set returned by the underlying system is
  104. * bitwise-disjoined into the key's current ready set. </p></li>
  105. *
  106. * </ol></li>
  107. *
  108. * If all of the keys in the key set at the start of this step have empty
  109. * interest sets then neither the selected-key set nor any of the keys'
  110. * ready-operation sets will be updated.
  111. *
  112. * <li><p> If any keys were added to the cancelled-key set while step (2) was
  113. * in progress then they are processed as in step (1). </p></li>
  114. *
  115. * </ol>
  116. *
  117. * <p> Whether or not a selection operation blocks to wait for one or more
  118. * channels to become ready, and if so for how long, is the only essential
  119. * difference between the three selection methods. </p>
  120. *
  121. *
  122. * <h4>Concurrency</h4>
  123. *
  124. * <p> Selectors are themselves safe for use by multiple concurrent threads;
  125. * their key sets, however, are not.
  126. *
  127. * <p> The selection operations synchronize on the selector itself, on the key
  128. * set, and on the selected-key set, in that order. They also synchronize on
  129. * the cancelled-key set during steps (1) and (3) above.
  130. *
  131. * <p> Changes made to the interest sets of a selector's keys while a
  132. * selection operation is in progress have no effect upon that operation; they
  133. * will be seen by the next selection operation.
  134. *
  135. * <p> Keys may be cancelled and channels may be closed at any time. Hence the
  136. * presence of a key in one or more of a selector's key sets does not imply
  137. * that the key is valid or that its channel is open. Application code should
  138. * be careful to synchronize and check these conditions as necessary if there
  139. * is any possibility that another thread will cancel a key or close a channel.
  140. *
  141. * <p> A thread blocked in one of the {@link #select()} or {@link
  142. * #select(long)} methods may be interrupted by some other thread in one of
  143. * three ways:
  144. *
  145. * <ul>
  146. *
  147. * <li><p> By invoking the selector's {@link #wakeup wakeup} method,
  148. * </p></li>
  149. *
  150. * <li><p> By invoking the selector's {@link #close close} method, or
  151. * </p></li>
  152. *
  153. * <li><p> By invoking the blocked thread's {@link
  154. * java.lang.Thread#interrupt() interrupt} method, in which case its
  155. * interrupt status will be set and the selector's {@link #wakeup wakeup}
  156. * method will be invoked. </p></li>
  157. *
  158. * </ul>
  159. *
  160. * <p> The {@link #close close} method synchronizes on the selector and all
  161. * three key sets in the same order as in a selection operation.
  162. *
  163. * <a name="ksc">
  164. *
  165. * <p> A selector's key and selected-key sets are not, in general, safe for use
  166. * by multiple concurrent threads. If such a thread might modify one of these
  167. * sets directly then access should be controlled by synchronizing on the set
  168. * itself. The iterators returned by these sets' {@link
  169. * java.util.Set#iterator() iterator} methods are <i>fail-fast:</i> If the set
  170. * is modified after the iterator is created, in any way except by invoking the
  171. * iterator's own {@link java.util.Iterator#remove() remove} method, then a
  172. * {@link java.util.ConcurrentModificationException} will be thrown. </p>
  173. *
  174. *
  175. * @author Mark Reinhold
  176. * @author JSR-51 Expert Group
  177. * @version 1.37, 04/05/05
  178. * @since 1.4
  179. *
  180. * @see SelectableChannel
  181. * @see SelectionKey
  182. */
  183. public abstract class Selector {
  184. /**
  185. * Initializes a new instance of this class.
  186. */
  187. protected Selector() { }
  188. /**
  189. * Opens a selector.
  190. *
  191. * <p> The new selector is created by invoking the {@link
  192. * java.nio.channels.spi.SelectorProvider#openSelector openSelector} method
  193. * of the system-wide default {@link
  194. * java.nio.channels.spi.SelectorProvider} object. </p>
  195. *
  196. * @return A new selector
  197. *
  198. * @throws IOException
  199. * If an I/O error occurs
  200. */
  201. public static Selector open() throws IOException {
  202. return SelectorProvider.provider().openSelector();
  203. }
  204. /**
  205. * Tells whether or not this selector is open. </p>
  206. *
  207. * @return <tt>true</tt> if, and only if, this selector is open
  208. */
  209. public abstract boolean isOpen();
  210. /**
  211. * Returns the provider that created this channel. </p>
  212. *
  213. * @return The provider that created this channel
  214. */
  215. public abstract SelectorProvider provider();
  216. /**
  217. * Returns this selector's key set.
  218. *
  219. * <p> The key set is not directly modifiable. A key is removed only after
  220. * it has been cancelled and its channel has been deregistered. Any
  221. * attempt to modify the key set will cause an {@link
  222. * UnsupportedOperationException} to be thrown.
  223. *
  224. * <p> The key set is <a href="#ksc">not thread-safe</a>. </p>
  225. *
  226. * @return This selector's key set
  227. *
  228. * @throws ClosedSelectorException
  229. * If this selector is closed
  230. */
  231. public abstract Set<SelectionKey> keys();
  232. /**
  233. * Returns this selector's selected-key set.
  234. *
  235. * <p> Keys may be removed from, but not directly added to, the
  236. * selected-key set. Any attempt to add an object to the key set will
  237. * cause an {@link UnsupportedOperationException} to be thrown.
  238. *
  239. * <p> The selected-key set is <a href="#ksc">not thread-safe</a>. </p>
  240. *
  241. * @return This selector's selected-key set
  242. *
  243. * @throws ClosedSelectorException
  244. * If this selector is closed
  245. */
  246. public abstract Set<SelectionKey> selectedKeys();
  247. /**
  248. * Selects a set of keys whose corresponding channels are ready for I/O
  249. * operations.
  250. *
  251. * <p> This method performs a non-blocking <a href="#selop">selection
  252. * operation</a>. If no channels have become selectable since the previous
  253. * selection operation then this method immediately returns zero.
  254. *
  255. * <p> Invoking this method clears the effect of any previous invocations
  256. * of the {@link #wakeup wakeup} method. </p>
  257. *
  258. * @return The number of keys, possibly zero, whose ready-operation sets
  259. * were updated by the selection operation
  260. *
  261. * @throws IOException
  262. * If an I/O error occurs
  263. *
  264. * @throws ClosedSelectorException
  265. * If this selector is closed
  266. */
  267. public abstract int selectNow() throws IOException;
  268. /**
  269. * Selects a set of keys whose corresponding channels are ready for I/O
  270. * operations.
  271. *
  272. * <p> This method performs a blocking <a href="#selop">selection
  273. * operation</a>. It returns only after at least one channel is selected,
  274. * this selector's {@link #wakeup wakeup} method is invoked, the current
  275. * thread is interrupted, or the given timeout period expires, whichever
  276. * comes first.
  277. *
  278. * <p> This method does not offer real-time guarantees: It schedules the
  279. * timeout as if by invoking the {@link Object#wait(long)} method. </p>
  280. *
  281. * @param timeout If positive, block for up to <tt>timeout</tt>
  282. * milliseconds, more or less, while waiting for a
  283. * channel to become ready; if zero, block indefinitely;
  284. * must not be negative
  285. *
  286. * @return The number of keys, possibly zero,
  287. * whose ready-operation sets were updated
  288. *
  289. * @throws IOException
  290. * If an I/O error occurs
  291. *
  292. * @throws ClosedSelectorException
  293. * If this selector is closed
  294. *
  295. * @throws IllegalArgumentException
  296. * If the value of the timeout argument is negative
  297. */
  298. public abstract int select(long timeout)
  299. throws IOException;
  300. /**
  301. * Selects a set of keys whose corresponding channels are ready for I/O
  302. * operations.
  303. *
  304. * <p> This method performs a blocking <a href="#selop">selection
  305. * operation</a>. It returns only after at least one channel is selected,
  306. * this selector's {@link #wakeup wakeup} method is invoked, or the current
  307. * thread is interrupted, whichever comes first. </p>
  308. *
  309. * @return The number of keys, possibly zero,
  310. * whose ready-operation sets were updated
  311. *
  312. * @throws IOException
  313. * If an I/O error occurs
  314. *
  315. * @throws ClosedSelectorException
  316. * If this selector is closed
  317. */
  318. public abstract int select() throws IOException;
  319. /**
  320. * Causes the first selection operation that has not yet returned to return
  321. * immediately.
  322. *
  323. * <p> If another thread is currently blocked in an invocation of the
  324. * {@link #select()} or {@link #select(long)} methods then that invocation
  325. * will return immediately. If no selection operation is currently in
  326. * progress then the next invocation of one of these methods will return
  327. * immediately unless the {@link #selectNow()} method is invoked in the
  328. * meantime. In any case the value returned by that invocation may be
  329. * non-zero. Subsequent invocations of the {@link #select()} or {@link
  330. * #select(long)} methods will block as usual unless this method is invoked
  331. * again in the meantime.
  332. *
  333. * <p> Invoking this method more than once between two successive selection
  334. * operations has the same effect as invoking it just once. </p>
  335. *
  336. * @return This selector
  337. */
  338. public abstract Selector wakeup();
  339. /**
  340. * Closes this selector.
  341. *
  342. * <p> If a thread is currently blocked in one of this selector's selection
  343. * methods then it is interrupted as if by invoking the selector's {@link
  344. * #wakeup wakeup} method.
  345. *
  346. * <p> Any uncancelled keys still associated with this selector are
  347. * invalidated, their channels are deregistered, and any other resources
  348. * associated with this selector are released.
  349. *
  350. * <p> If this selector is already closed then invoking this method has no
  351. * effect.
  352. *
  353. * <p> After a selector is closed, any further attempt to use it, except by
  354. * invoking this method or the {@link #wakeup wakeup} method, will cause a
  355. * {@link ClosedSelectorException} to be thrown. </p>
  356. *
  357. * @throws IOException
  358. * If an I/O error occurs
  359. */
  360. public abstract void close() throws IOException;
  361. }