1 /* Licensed to the Apache Software Foundation (ASF) under one or more 2 * contributor license agreements. See the NOTICE file distributed with 3 * this work for additional information regarding copyright ownership. 4 * The ASF licenses this file to You under the Apache License, Version 2.0 5 * (the "License"); you may not use this file except in compliance with 6 * the License. You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package java.nio; 18 19 import java.nio.channels.CancelledKeyException; 20 import java.nio.channels.SelectableChannel; 21 import java.nio.channels.SelectionKey; 22 import java.nio.channels.Selector; 23 import java.nio.channels.SocketChannel; 24 import java.nio.channels.spi.AbstractSelectableChannel; 25 import java.nio.channels.spi.AbstractSelectionKey; 26 27 /** 28 * Default implementation of SelectionKey 29 */ 30 final class SelectionKeyImpl extends AbstractSelectionKey { 31 32 private AbstractSelectableChannel channel; 33 34 private int interestOps; 35 36 private int readyOps; 37 38 private SelectorImpl selector; 39 40 public SelectionKeyImpl(AbstractSelectableChannel channel, int operations, 41 Object attachment, SelectorImpl selector) { 42 this.channel = channel; 43 interestOps = operations; 44 this.selector = selector; 45 attach(attachment); 46 } 47 48 @Override 49 public SelectableChannel channel() { 50 return channel; 51 } 52 53 @Override 54 public int interestOps() { 55 checkValid(); 56 synchronized (selector.keysLock) { 57 return interestOps; 58 } 59 } 60 61 int interestOpsNoCheck() { 62 synchronized (selector.keysLock) { 63 return interestOps; 64 } 65 } 66 67 @Override 68 public SelectionKey interestOps(int operations) { 69 checkValid(); 70 if ((operations & ~(channel().validOps())) != 0) { 71 throw new IllegalArgumentException(); 72 } 73 synchronized (selector.keysLock) { 74 interestOps = operations; 75 } 76 return this; 77 } 78 79 @Override 80 public int readyOps() { 81 checkValid(); 82 return readyOps; 83 } 84 85 @Override 86 public Selector selector() { 87 return selector; 88 } 89 90 /* 91 * package private method for setting the ready operation by selector 92 */ 93 void setReadyOps(int readyOps) { 94 this.readyOps = readyOps; 95 } 96 97 private void checkValid() { 98 if (!isValid()) { 99 throw new CancelledKeyException(); 100 } 101 } 102 103 /** 104 * Returns true if the channel for this key is connected. If the channel 105 * does not need connecting, this always return true. 106 */ 107 boolean isConnected() { 108 return !(channel instanceof SocketChannel) || ((SocketChannel) channel).isConnected(); 109 } 110 } 111