01: /*
02: * Copyright 2002-2006 Sun Microsystems, Inc. All Rights Reserved.
03: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
04: *
05: * This code is free software; you can redistribute it and/or modify it
06: * under the terms of the GNU General Public License version 2 only, as
07: * published by the Free Software Foundation. Sun designates this
08: * particular file as subject to the "Classpath" exception as provided
09: * by Sun in the LICENSE file that accompanied this code.
10: *
11: * This code is distributed in the hope that it will be useful, but WITHOUT
12: * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13: * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14: * version 2 for more details (a copy is included in the LICENSE file that
15: * accompanied this code).
16: *
17: * You should have received a copy of the GNU General Public License version
18: * 2 along with this work; if not, write to the Free Software Foundation,
19: * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20: *
21: * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
22: * CA 95054 USA or visit www.sun.com if you need additional information or
23: * have any questions.
24: */
25:
26: package sun.nio.ch;
27:
28: // Special-purpose data structure for sets of native threads
29:
30: class NativeThreadSet {
31:
32: private long[] elts;
33: private int used = 0;
34:
35: NativeThreadSet(int n) {
36: elts = new long[n];
37: }
38:
39: // Adds the current native thread to this set, returning its index so that
40: // it can efficiently be removed later.
41: //
42: int add() {
43: long th = NativeThread.current();
44: if (th <= 0)
45: return -1;
46: synchronized (this ) {
47: int start = 0;
48: if (used >= elts.length) {
49: int on = elts.length;
50: int nn = on * 2;
51: long[] nelts = new long[nn];
52: System.arraycopy(elts, 0, nelts, 0, on);
53: elts = nelts;
54: start = on;
55: }
56: for (int i = start; i < elts.length; i++) {
57: if (elts[i] == 0) {
58: elts[i] = th;
59: used++;
60: return i;
61: }
62: }
63: assert false;
64: return -1;
65: }
66: }
67:
68: // Removes the thread at the given index.
69: //
70: void remove(int i) {
71: if (i < 0)
72: return;
73: synchronized (this ) {
74: elts[i] = 0;
75: used--;
76: }
77: }
78:
79: // Signals all threads in this set.
80: //
81: void signal() {
82: synchronized (this ) {
83: int u = used;
84: int n = elts.length;
85: for (int i = 0; i < n; i++) {
86: long th = elts[i];
87: if (th == 0)
88: continue;
89: NativeThread.signal(th);
90: if (--u == 0)
91: break;
92: }
93: }
94: }
95:
96: }
|