Path: blob/master/src/java.base/share/classes/java/nio/channels/spi/AbstractSelectableChannel.java
41161 views
/*1* Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package java.nio.channels.spi;2627import java.io.IOException;28import java.nio.channels.CancelledKeyException;29import java.nio.channels.ClosedChannelException;30import java.nio.channels.ClosedSelectorException;31import java.nio.channels.IllegalBlockingModeException;32import java.nio.channels.IllegalSelectorException;33import java.nio.channels.SelectableChannel;34import java.nio.channels.SelectionKey;35import java.nio.channels.Selector;36import java.util.Arrays;37import java.util.function.Consumer;383940/**41* Base implementation class for selectable channels.42*43* <p> This class defines methods that handle the mechanics of channel44* registration, deregistration, and closing. It maintains the current45* blocking mode of this channel as well as its current set of selection keys.46* It performs all of the synchronization required to implement the {@link47* java.nio.channels.SelectableChannel} specification. Implementations of the48* protected abstract methods defined in this class need not synchronize49* against other threads that might be engaged in the same operations. </p>50*51*52* @author Mark Reinhold53* @author Mike McCloskey54* @author JSR-51 Expert Group55* @since 1.456*/5758public abstract class AbstractSelectableChannel59extends SelectableChannel60{6162// The provider that created this channel63private final SelectorProvider provider;6465// Keys that have been created by registering this channel with selectors.66// They are saved because if this channel is closed the keys must be67// deregistered. Protected by keyLock.68//69private SelectionKey[] keys = null;70private int keyCount = 0;7172// Lock for key set and count73private final Object keyLock = new Object();7475// Lock for registration and configureBlocking operations76private final Object regLock = new Object();7778// True when non-blocking, need regLock to change;79private volatile boolean nonBlocking;8081/**82* Initializes a new instance of this class.83*84* @param provider85* The provider that created this channel86*/87protected AbstractSelectableChannel(SelectorProvider provider) {88this.provider = provider;89}9091/**92* Returns the provider that created this channel.93*94* @return The provider that created this channel95*/96public final SelectorProvider provider() {97return provider;98}99100101// -- Utility methods for the key set --102103private void addKey(SelectionKey k) {104assert Thread.holdsLock(keyLock);105int i = 0;106if ((keys != null) && (keyCount < keys.length)) {107// Find empty element of key array108for (i = 0; i < keys.length; i++)109if (keys[i] == null)110break;111} else if (keys == null) {112keys = new SelectionKey[2];113} else {114// Grow key array115int n = keys.length * 2;116SelectionKey[] ks = new SelectionKey[n];117for (i = 0; i < keys.length; i++)118ks[i] = keys[i];119keys = ks;120i = keyCount;121}122keys[i] = k;123keyCount++;124}125126private SelectionKey findKey(Selector sel) {127assert Thread.holdsLock(keyLock);128if (keys == null)129return null;130for (int i = 0; i < keys.length; i++)131if ((keys[i] != null) && (keys[i].selector() == sel))132return keys[i];133return null;134135}136137void removeKey(SelectionKey k) { // package-private138synchronized (keyLock) {139for (int i = 0; i < keys.length; i++)140if (keys[i] == k) {141keys[i] = null;142keyCount--;143}144((AbstractSelectionKey)k).invalidate();145}146}147148private boolean haveValidKeys() {149synchronized (keyLock) {150if (keyCount == 0)151return false;152for (int i = 0; i < keys.length; i++) {153if ((keys[i] != null) && keys[i].isValid())154return true;155}156return false;157}158}159160161// -- Registration --162163public final boolean isRegistered() {164synchronized (keyLock) {165return keyCount != 0;166}167}168169public final SelectionKey keyFor(Selector sel) {170synchronized (keyLock) {171return findKey(sel);172}173}174175/**176* Invokes an action for each key.177*178* This method is invoked by DatagramChannelImpl::disconnect.179*/180private void forEach(Consumer<SelectionKey> action) {181synchronized (keyLock) {182SelectionKey[] keys = this.keys;183if (keys != null) {184Arrays.stream(keys).filter(k -> k != null).forEach(action::accept);185}186}187}188189/**190* Registers this channel with the given selector, returning a selection key.191*192* <p> This method first verifies that this channel is open and that the193* given initial interest set is valid.194*195* <p> If this channel is already registered with the given selector then196* the selection key representing that registration is returned after197* setting its interest set to the given value.198*199* <p> Otherwise this channel has not yet been registered with the given200* selector, so the {@link AbstractSelector#register register} method of201* the selector is invoked while holding the appropriate locks. The202* resulting key is added to this channel's key set before being returned.203* </p>204*205* @throws ClosedSelectorException {@inheritDoc}206*207* @throws IllegalBlockingModeException {@inheritDoc}208*209* @throws IllegalSelectorException {@inheritDoc}210*211* @throws CancelledKeyException {@inheritDoc}212*213* @throws IllegalArgumentException {@inheritDoc}214*/215public final SelectionKey register(Selector sel, int ops, Object att)216throws ClosedChannelException217{218if ((ops & ~validOps()) != 0)219throw new IllegalArgumentException();220if (!isOpen())221throw new ClosedChannelException();222synchronized (regLock) {223if (isBlocking())224throw new IllegalBlockingModeException();225synchronized (keyLock) {226// re-check if channel has been closed227if (!isOpen())228throw new ClosedChannelException();229SelectionKey k = findKey(sel);230if (k != null) {231k.attach(att);232k.interestOps(ops);233} else {234// New registration235k = ((AbstractSelector)sel).register(this, ops, att);236addKey(k);237}238return k;239}240}241}242243244// -- Closing --245246/**247* Closes this channel.248*249* <p> This method, which is specified in the {@link250* AbstractInterruptibleChannel} class and is invoked by the {@link251* java.nio.channels.Channel#close close} method, in turn invokes the252* {@link #implCloseSelectableChannel implCloseSelectableChannel} method in253* order to perform the actual work of closing this channel. It then254* cancels all of this channel's keys. </p>255*/256protected final void implCloseChannel() throws IOException {257implCloseSelectableChannel();258259// clone keys to avoid calling cancel when holding keyLock260SelectionKey[] copyOfKeys = null;261synchronized (keyLock) {262if (keys != null) {263copyOfKeys = keys.clone();264}265}266267if (copyOfKeys != null) {268for (SelectionKey k : copyOfKeys) {269if (k != null) {270k.cancel(); // invalidate and adds key to cancelledKey set271}272}273}274}275276/**277* Closes this selectable channel.278*279* <p> This method is invoked by the {@link java.nio.channels.Channel#close280* close} method in order to perform the actual work of closing the281* channel. This method is only invoked if the channel has not yet been282* closed, and it is never invoked more than once.283*284* <p> An implementation of this method must arrange for any other thread285* that is blocked in an I/O operation upon this channel to return286* immediately, either by throwing an exception or by returning normally.287* </p>288*289* @throws IOException290* If an I/O error occurs291*/292protected abstract void implCloseSelectableChannel() throws IOException;293294295// -- Blocking --296297public final boolean isBlocking() {298return !nonBlocking;299}300301public final Object blockingLock() {302return regLock;303}304305/**306* Adjusts this channel's blocking mode.307*308* <p> If the given blocking mode is different from the current blocking309* mode then this method invokes the {@link #implConfigureBlocking310* implConfigureBlocking} method, while holding the appropriate locks, in311* order to change the mode. </p>312*/313public final SelectableChannel configureBlocking(boolean block)314throws IOException315{316synchronized (regLock) {317if (!isOpen())318throw new ClosedChannelException();319boolean blocking = !nonBlocking;320if (block != blocking) {321if (block && haveValidKeys())322throw new IllegalBlockingModeException();323implConfigureBlocking(block);324nonBlocking = !block;325}326}327return this;328}329330/**331* Adjusts this channel's blocking mode.332*333* <p> This method is invoked by the {@link #configureBlocking334* configureBlocking} method in order to perform the actual work of335* changing the blocking mode. This method is only invoked if the new mode336* is different from the current mode. </p>337*338* @param block If {@code true} then this channel will be placed in339* blocking mode; if {@code false} then it will be placed340* non-blocking mode341*342* @throws IOException343* If an I/O error occurs344*/345protected abstract void implConfigureBlocking(boolean block)346throws IOException;347348}349350351