001 /*
002 * Copyright 2000-2006 Sun Microsystems, Inc. All Rights Reserved.
003 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
004 *
005 * This code is free software; you can redistribute it and/or modify it
006 * under the terms of the GNU General Public License version 2 only, as
007 * published by the Free Software Foundation. Sun designates this
008 * particular file as subject to the "Classpath" exception as provided
009 * by Sun in the LICENSE file that accompanied this code.
010 *
011 * This code is distributed in the hope that it will be useful, but WITHOUT
012 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
013 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
014 * version 2 for more details (a copy is included in the LICENSE file that
015 * accompanied this code).
016 *
017 * You should have received a copy of the GNU General Public License version
018 * 2 along with this work; if not, write to the Free Software Foundation,
019 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
020 *
021 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
022 * CA 95054 USA or visit www.sun.com if you need additional information or
023 * have any questions.
024 */
025
026 package java.nio.channels;
027
028 import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
029 import java.io.IOException;
030
031 /**
032 * A token representing the registration of a {@link SelectableChannel} with a
033 * {@link Selector}.
034 *
035 * <p> A selection key is created each time a channel is registered with a
036 * selector. A key remains valid until it is <i>cancelled</i> by invoking its
037 * {@link #cancel cancel} method, by closing its channel, or by closing its
038 * selector. Cancelling a key does not immediately remove it from its
039 * selector; it is instead added to the selector's <a
040 * href="Selector.html#ks"><i>cancelled-key set</i></a> for removal during the
041 * next selection operation. The validity of a key may be tested by invoking
042 * its {@link #isValid isValid} method.
043 *
044 * <a name="opsets">
045 *
046 * <p> A selection key contains two <i>operation sets</i> represented as
047 * integer values. Each bit of an operation set denotes a category of
048 * selectable operations that are supported by the key's channel.
049 *
050 * <ul>
051 *
052 * <li><p> The <i>interest set</i> determines which operation categories will
053 * be tested for readiness the next time one of the selector's selection
054 * methods is invoked. The interest set is initialized with the value given
055 * when the key is created; it may later be changed via the {@link
056 * #interestOps(int)} method. </p></li>
057 *
058 * <li><p> The <i>ready set</i> identifies the operation categories for which
059 * the key's channel has been detected to be ready by the key's selector.
060 * The ready set is initialized to zero when the key is created; it may later
061 * be updated by the selector during a selection operation, but it cannot be
062 * updated directly. </p></li>
063 *
064 * </ul>
065 *
066 * <p> That a selection key's ready set indicates that its channel is ready for
067 * some operation category is a hint, but not a guarantee, that an operation in
068 * such a category may be performed by a thread without causing the thread to
069 * block. A ready set is most likely to be accurate immediately after the
070 * completion of a selection operation. It is likely to be made inaccurate by
071 * external events and by I/O operations that are invoked upon the
072 * corresponding channel.
073 *
074 * <p> This class defines all known operation-set bits, but precisely which
075 * bits are supported by a given channel depends upon the type of the channel.
076 * Each subclass of {@link SelectableChannel} defines an {@link
077 * SelectableChannel#validOps() validOps()} method which returns a set
078 * identifying just those operations that are supported by the channel. An
079 * attempt to set or test an operation-set bit that is not supported by a key's
080 * channel will result in an appropriate run-time exception.
081 *
082 * <p> It is often necessary to associate some application-specific data with a
083 * selection key, for example an object that represents the state of a
084 * higher-level protocol and handles readiness notifications in order to
085 * implement that protocol. Selection keys therefore support the
086 * <i>attachment</i> of a single arbitrary object to a key. An object can be
087 * attached via the {@link #attach attach} method and then later retrieved via
088 * the {@link #attachment() attachment} method.
089 *
090 * <p> Selection keys are safe for use by multiple concurrent threads. The
091 * operations of reading and writing the interest set will, in general, be
092 * synchronized with certain operations of the selector. Exactly how this
093 * synchronization is performed is implementation-dependent: In a naive
094 * implementation, reading or writing the interest set may block indefinitely
095 * if a selection operation is already in progress; in a high-performance
096 * implementation, reading or writing the interest set may block briefly, if at
097 * all. In any case, a selection operation will always use the interest-set
098 * value that was current at the moment that the operation began. </p>
099 *
100 *
101 * @author Mark Reinhold
102 * @author JSR-51 Expert Group
103 * @version 1.33, 07/05/05
104 * @since 1.4
105 *
106 * @see SelectableChannel
107 * @see Selector
108 */
109
110 public abstract class SelectionKey {
111
112 /**
113 * Constructs an instance of this class.
114 */
115 protected SelectionKey() {
116 }
117
118 // -- Channel and selector operations --
119
120 /**
121 * Returns the channel for which this key was created. This method will
122 * continue to return the channel even after the key is cancelled. </p>
123 *
124 * @return This key's channel
125 */
126 public abstract SelectableChannel channel();
127
128 /**
129 * Returns the selector for which this key was created. This method will
130 * continue to return the selector even after the key is cancelled. </p>
131 *
132 * @return This key's selector
133 */
134 public abstract Selector selector();
135
136 /**
137 * Tells whether or not this key is valid.
138 *
139 * <p> A key is valid upon creation and remains so until it is cancelled,
140 * its channel is closed, or its selector is closed. </p>
141 *
142 * @return <tt>true</tt> if, and only if, this key is valid
143 */
144 public abstract boolean isValid();
145
146 /**
147 * Requests that the registration of this key's channel with its selector
148 * be cancelled. Upon return the key will be invalid and will have been
149 * added to its selector's cancelled-key set. The key will be removed from
150 * all of the selector's key sets during the next selection operation.
151 *
152 * <p> If this key has already been cancelled then invoking this method has
153 * no effect. Once cancelled, a key remains forever invalid. </p>
154 *
155 * <p> This method may be invoked at any time. It synchronizes on the
156 * selector's cancelled-key set, and therefore may block briefly if invoked
157 * concurrently with a cancellation or selection operation involving the
158 * same selector. </p>
159 */
160 public abstract void cancel();
161
162 // -- Operation-set accessors --
163
164 /**
165 * Retrieves this key's interest set.
166 *
167 * <p> It is guaranteed that the returned set will only contain operation
168 * bits that are valid for this key's channel.
169 *
170 * <p> This method may be invoked at any time. Whether or not it blocks,
171 * and for how long, is implementation-dependent. </p>
172 *
173 * @return This key's interest set
174 *
175 * @throws CancelledKeyException
176 * If this key has been cancelled
177 */
178 public abstract int interestOps();
179
180 /**
181 * Sets this key's interest set to the given value.
182 *
183 * <p> This method may be invoked at any time. Whether or not it blocks,
184 * and for how long, is implementation-dependent. </p>
185 *
186 * @param ops The new interest set
187 *
188 * @return This selection key
189 *
190 * @throws IllegalArgumentException
191 * If a bit in the set does not correspond to an operation that
192 * is supported by this key's channel, that is, if
193 * <tt>set & ~(channel().validOps()) != 0</tt>
194 *
195 * @throws CancelledKeyException
196 * If this key has been cancelled
197 */
198 public abstract SelectionKey interestOps(int ops);
199
200 /**
201 * Retrieves this key's ready-operation set.
202 *
203 * <p> It is guaranteed that the returned set will only contain operation
204 * bits that are valid for this key's channel. </p>
205 *
206 * @return This key's ready-operation set
207 *
208 * @throws CancelledKeyException
209 * If this key has been cancelled
210 */
211 public abstract int readyOps();
212
213 // -- Operation bits and bit-testing convenience methods --
214
215 /**
216 * Operation-set bit for read operations.
217 *
218 * <p> Suppose that a selection key's interest set contains
219 * <tt>OP_READ</tt> at the start of a <a
220 * href="Selector.html#selop">selection operation</a>. If the selector
221 * detects that the corresponding channel is ready for reading, has reached
222 * end-of-stream, has been remotely shut down for further reading, or has
223 * an error pending, then it will add <tt>OP_READ</tt> to the key's
224 * ready-operation set and add the key to its selected-key set. </p>
225 */
226 public static final int OP_READ = 1 << 0;
227
228 /**
229 * Operation-set bit for write operations. </p>
230 *
231 * <p> Suppose that a selection key's interest set contains
232 * <tt>OP_WRITE</tt> at the start of a <a
233 * href="Selector.html#selop">selection operation</a>. If the selector
234 * detects that the corresponding channel is ready for writing, has been
235 * remotely shut down for further writing, or has an error pending, then it
236 * will add <tt>OP_WRITE</tt> to the key's ready set and add the key to its
237 * selected-key set. </p>
238 */
239 public static final int OP_WRITE = 1 << 2;
240
241 /**
242 * Operation-set bit for socket-connect operations. </p>
243 *
244 * <p> Suppose that a selection key's interest set contains
245 * <tt>OP_CONNECT</tt> at the start of a <a
246 * href="Selector.html#selop">selection operation</a>. If the selector
247 * detects that the corresponding socket channel is ready to complete its
248 * connection sequence, or has an error pending, then it will add
249 * <tt>OP_CONNECT</tt> to the key's ready set and add the key to its
250 * selected-key set. </p>
251 */
252 public static final int OP_CONNECT = 1 << 3;
253
254 /**
255 * Operation-set bit for socket-accept operations. </p>
256 *
257 * <p> Suppose that a selection key's interest set contains
258 * <tt>OP_ACCEPT</tt> at the start of a <a
259 * href="Selector.html#selop">selection operation</a>. If the selector
260 * detects that the corresponding server-socket channel is ready to accept
261 * another connection, or has an error pending, then it will add
262 * <tt>OP_ACCEPT</tt> to the key's ready set and add the key to its
263 * selected-key set. </p>
264 */
265 public static final int OP_ACCEPT = 1 << 4;
266
267 /**
268 * Tests whether this key's channel is ready for reading.
269 *
270 * <p> An invocation of this method of the form <tt>k.isReadable()</tt>
271 * behaves in exactly the same way as the expression
272 *
273 * <blockquote><pre>
274 * k.readyOps() & OP_READ != 0</pre></blockquote>
275 *
276 * <p> If this key's channel does not support read operations then this
277 * method always returns <tt>false</tt>. </p>
278 *
279 * @return <tt>true</tt> if, and only if,
280 * <tt>readyOps()</tt> <tt>&</tt> <tt>OP_READ</tt> is
281 * nonzero
282 *
283 * @throws CancelledKeyException
284 * If this key has been cancelled
285 */
286 public final boolean isReadable() {
287 return (readyOps() & OP_READ) != 0;
288 }
289
290 /**
291 * Tests whether this key's channel is ready for writing.
292 *
293 * <p> An invocation of this method of the form <tt>k.isWritable()</tt>
294 * behaves in exactly the same way as the expression
295 *
296 * <blockquote><pre>
297 * k.readyOps() & OP_WRITE != 0</pre></blockquote>
298 *
299 * <p> If this key's channel does not support write operations then this
300 * method always returns <tt>false</tt>. </p>
301 *
302 * @return <tt>true</tt> if, and only if,
303 * <tt>readyOps()</tt> <tt>&</tt> <tt>OP_WRITE</tt>
304 * is nonzero
305 *
306 * @throws CancelledKeyException
307 * If this key has been cancelled
308 */
309 public final boolean isWritable() {
310 return (readyOps() & OP_WRITE) != 0;
311 }
312
313 /**
314 * Tests whether this key's channel has either finished, or failed to
315 * finish, its socket-connection operation.
316 *
317 * <p> An invocation of this method of the form <tt>k.isConnectable()</tt>
318 * behaves in exactly the same way as the expression
319 *
320 * <blockquote><pre>
321 * k.readyOps() & OP_CONNECT != 0</pre></blockquote>
322 *
323 * <p> If this key's channel does not support socket-connect operations
324 * then this method always returns <tt>false</tt>. </p>
325 *
326 * @return <tt>true</tt> if, and only if,
327 * <tt>readyOps()</tt> <tt>&</tt> <tt>OP_CONNECT</tt>
328 * is nonzero
329 *
330 * @throws CancelledKeyException
331 * If this key has been cancelled
332 */
333 public final boolean isConnectable() {
334 return (readyOps() & OP_CONNECT) != 0;
335 }
336
337 /**
338 * Tests whether this key's channel is ready to accept a new socket
339 * connection.
340 *
341 * <p> An invocation of this method of the form <tt>k.isAcceptable()</tt>
342 * behaves in exactly the same way as the expression
343 *
344 * <blockquote><pre>
345 * k.readyOps() & OP_ACCEPT != 0</pre></blockquote>
346 *
347 * <p> If this key's channel does not support socket-accept operations then
348 * this method always returns <tt>false</tt>. </p>
349 *
350 * @return <tt>true</tt> if, and only if,
351 * <tt>readyOps()</tt> <tt>&</tt> <tt>OP_ACCEPT</tt>
352 * is nonzero
353 *
354 * @throws CancelledKeyException
355 * If this key has been cancelled
356 */
357 public final boolean isAcceptable() {
358 return (readyOps() & OP_ACCEPT) != 0;
359 }
360
361 // -- Attachments --
362
363 private volatile Object attachment = null;
364
365 private static final AtomicReferenceFieldUpdater<SelectionKey, Object> attachmentUpdater = AtomicReferenceFieldUpdater
366 .newUpdater(SelectionKey.class, Object.class, "attachment");
367
368 /**
369 * Attaches the given object to this key.
370 *
371 * <p> An attached object may later be retrieved via the {@link #attachment()
372 * attachment} method. Only one object may be attached at a time; invoking
373 * this method causes any previous attachment to be discarded. The current
374 * attachment may be discarded by attaching <tt>null</tt>. </p>
375 *
376 * @param ob
377 * The object to be attached; may be <tt>null</tt>
378 *
379 * @return The previously-attached object, if any,
380 * otherwise <tt>null</tt>
381 */
382 public final Object attach(Object ob) {
383 return attachmentUpdater.getAndSet(this , ob);
384 }
385
386 /**
387 * Retrieves the current attachment. </p>
388 *
389 * @return The object currently attached to this key,
390 * or <tt>null</tt> if there is no attachment
391 */
392 public final Object attachment() {
393 return attachment;
394 }
395
396 }
|