Path: blob/master/src/java.base/share/classes/sun/nio/ch/NativeThreadSet.java
41159 views
/*1* Copyright (c) 2002, 2012, 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 sun.nio.ch;262728// Special-purpose data structure for sets of native threads293031class NativeThreadSet {3233private long[] elts;34private int used = 0;35private boolean waitingToEmpty;3637NativeThreadSet(int n) {38elts = new long[n];39}4041// Adds the current native thread to this set, returning its index so that42// it can efficiently be removed later.43//44int add() {45long th = NativeThread.current();46// 0 and -1 are treated as placeholders, not real thread handles47if (th == 0)48th = -1;49synchronized (this) {50int start = 0;51if (used >= elts.length) {52int on = elts.length;53int nn = on * 2;54long[] nelts = new long[nn];55System.arraycopy(elts, 0, nelts, 0, on);56elts = nelts;57start = on;58}59for (int i = start; i < elts.length; i++) {60if (elts[i] == 0) {61elts[i] = th;62used++;63return i;64}65}66assert false;67return -1;68}69}7071// Removes the thread at the given index.72//73void remove(int i) {74synchronized (this) {75elts[i] = 0;76used--;77if (used == 0 && waitingToEmpty)78notifyAll();79}80}8182// Signals all threads in this set.83//84synchronized void signalAndWait() {85boolean interrupted = false;86while (used > 0) {87int u = used;88int n = elts.length;89for (int i = 0; i < n; i++) {90long th = elts[i];91if (th == 0)92continue;93if (th != -1)94NativeThread.signal(th);95if (--u == 0)96break;97}98waitingToEmpty = true;99try {100wait(50);101} catch (InterruptedException e) {102interrupted = true;103} finally {104waitingToEmpty = false;105}106}107if (interrupted)108Thread.currentThread().interrupt();109}110}111112113