Path: blob/master/src/java.base/share/classes/java/nio/channels/spi/AbstractSelectionKey.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.lang.invoke.MethodHandles;28import java.lang.invoke.VarHandle;29import java.nio.channels.SelectionKey;30import java.nio.channels.Selector;3132import sun.nio.ch.SelectionKeyImpl;33import sun.nio.ch.SelectorImpl;3435/**36* Base implementation class for selection keys.37*38* <p> This class tracks the validity of the key and implements cancellation.39*40* @author Mark Reinhold41* @author JSR-51 Expert Group42* @since 1.443*/4445public abstract class AbstractSelectionKey46extends SelectionKey47{48private static final VarHandle INVALID;49static {50try {51MethodHandles.Lookup l = MethodHandles.lookup();52INVALID = l.findVarHandle(AbstractSelectionKey.class, "invalid", boolean.class);53} catch (Exception e) {54throw new InternalError(e);55}56}5758/**59* Initializes a new instance of this class.60*/61protected AbstractSelectionKey() { }6263private volatile boolean invalid;6465public final boolean isValid() {66return !invalid;67}6869void invalidate() { // package-private70invalid = true;71}7273/**74* Cancels this key.75*76* <p> If this key has not yet been cancelled then it is added to its77* selector's cancelled-key set while synchronized on that set. </p>78*/79public final void cancel() {80boolean changed = (boolean) INVALID.compareAndSet(this, false, true);81if (changed) {82Selector sel = selector();83if (sel instanceof SelectorImpl) {84// queue cancelled key directly85((SelectorImpl) sel).cancel((SelectionKeyImpl) this);86} else {87((AbstractSelector) sel).cancel(this);88}89}90}91}929394