Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/mobile
Path: blob/master/src/java.base/macosx/classes/sun/nio/ch/KQueuePort.java
41137 views
1
/*
2
* Copyright (c) 2012, 2018, Oracle and/or its affiliates. All rights reserved.
3
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4
*
5
* This code is free software; you can redistribute it and/or modify it
6
* under the terms of the GNU General Public License version 2 only, as
7
* published by the Free Software Foundation. Oracle designates this
8
* particular file as subject to the "Classpath" exception as provided
9
* by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22
* or visit www.oracle.com if you need additional information or have any
23
* questions.
24
*/
25
26
package sun.nio.ch;
27
28
import java.nio.channels.spi.AsynchronousChannelProvider;
29
import java.io.IOException;
30
import java.util.concurrent.ArrayBlockingQueue;
31
import java.util.concurrent.RejectedExecutionException;
32
import java.util.concurrent.atomic.AtomicInteger;
33
34
import static sun.nio.ch.KQueue.EVFILT_READ;
35
import static sun.nio.ch.KQueue.EVFILT_WRITE;
36
import static sun.nio.ch.KQueue.EV_ADD;
37
import static sun.nio.ch.KQueue.EV_ONESHOT;
38
39
/**
40
* AsynchronousChannelGroup implementation based on the BSD kqueue facility.
41
*/
42
43
final class KQueuePort
44
extends Port
45
{
46
// maximum number of events to poll at a time
47
private static final int MAX_KEVENTS_TO_POLL = 512;
48
49
// kqueue file descriptor
50
private final int kqfd;
51
52
// address of the poll array passed to kqueue_wait
53
private final long address;
54
55
// true if kqueue closed
56
private boolean closed;
57
58
// socket pair used for wakeup
59
private final int sp[];
60
61
// number of wakeups pending
62
private final AtomicInteger wakeupCount = new AtomicInteger();
63
64
// encapsulates an event for a channel
65
static class Event {
66
final PollableChannel channel;
67
final int events;
68
69
Event(PollableChannel channel, int events) {
70
this.channel = channel;
71
this.events = events;
72
}
73
74
PollableChannel channel() { return channel; }
75
int events() { return events; }
76
}
77
78
// queue of events for cases that a polling thread dequeues more than one
79
// event
80
private final ArrayBlockingQueue<Event> queue;
81
private final Event NEED_TO_POLL = new Event(null, 0);
82
private final Event EXECUTE_TASK_OR_SHUTDOWN = new Event(null, 0);
83
84
KQueuePort(AsynchronousChannelProvider provider, ThreadPool pool)
85
throws IOException
86
{
87
super(provider, pool);
88
89
this.kqfd = KQueue.create();
90
this.address = KQueue.allocatePollArray(MAX_KEVENTS_TO_POLL);
91
92
// create socket pair for wakeup mechanism
93
try {
94
long fds = IOUtil.makePipe(true);
95
this.sp = new int[]{(int) (fds >>> 32), (int) fds};
96
} catch (IOException ioe) {
97
KQueue.freePollArray(address);
98
FileDispatcherImpl.closeIntFD(kqfd);
99
throw ioe;
100
}
101
102
// register one end with kqueue
103
KQueue.register(kqfd, sp[0], EVFILT_READ, EV_ADD);
104
105
// create the queue and offer the special event to ensure that the first
106
// threads polls
107
this.queue = new ArrayBlockingQueue<>(MAX_KEVENTS_TO_POLL);
108
this.queue.offer(NEED_TO_POLL);
109
}
110
111
KQueuePort start() {
112
startThreads(new EventHandlerTask());
113
return this;
114
}
115
116
/**
117
* Release all resources
118
*/
119
private void implClose() {
120
synchronized (this) {
121
if (closed)
122
return;
123
closed = true;
124
}
125
126
try { FileDispatcherImpl.closeIntFD(kqfd); } catch (IOException ioe) { }
127
try { FileDispatcherImpl.closeIntFD(sp[0]); } catch (IOException ioe) { }
128
try { FileDispatcherImpl.closeIntFD(sp[1]); } catch (IOException ioe) { }
129
KQueue.freePollArray(address);
130
}
131
132
private void wakeup() {
133
if (wakeupCount.incrementAndGet() == 1) {
134
// write byte to socketpair to force wakeup
135
try {
136
IOUtil.write1(sp[1], (byte)0);
137
} catch (IOException x) {
138
throw new AssertionError(x);
139
}
140
}
141
}
142
143
@Override
144
void executeOnHandlerTask(Runnable task) {
145
synchronized (this) {
146
if (closed)
147
throw new RejectedExecutionException();
148
offerTask(task);
149
wakeup();
150
}
151
}
152
153
@Override
154
void shutdownHandlerTasks() {
155
/*
156
* If no tasks are running then just release resources; otherwise
157
* write to the one end of the socketpair to wakeup any polling threads.
158
*/
159
int nThreads = threadCount();
160
if (nThreads == 0) {
161
implClose();
162
} else {
163
// send wakeup to each thread
164
while (nThreads-- > 0) {
165
wakeup();
166
}
167
}
168
}
169
170
// invoked by clients to register a file descriptor
171
@Override
172
void startPoll(int fd, int events) {
173
// We use a separate filter for read and write events.
174
// TBD: Measure cost of EV_ONESHOT vs. EV_CLEAR, either will do here.
175
int err = 0;
176
int flags = (EV_ADD|EV_ONESHOT);
177
if ((events & Net.POLLIN) > 0)
178
err = KQueue.register(kqfd, fd, EVFILT_READ, flags);
179
if (err == 0 && (events & Net.POLLOUT) > 0)
180
err = KQueue.register(kqfd, fd, EVFILT_WRITE, flags);
181
if (err != 0)
182
throw new InternalError("kevent failed: " + err); // should not happen
183
}
184
185
/**
186
* Task to process events from kqueue and dispatch to the channel's
187
* onEvent handler.
188
*
189
* Events are retrieved from kqueue in batch and offered to a BlockingQueue
190
* where they are consumed by handler threads. A special "NEED_TO_POLL"
191
* event is used to signal one consumer to re-poll when all events have
192
* been consumed.
193
*/
194
private class EventHandlerTask implements Runnable {
195
private Event poll() throws IOException {
196
try {
197
for (;;) {
198
int n;
199
do {
200
n = KQueue.poll(kqfd, address, MAX_KEVENTS_TO_POLL, -1L);
201
} while (n == IOStatus.INTERRUPTED);
202
203
/**
204
* 'n' events have been read. Here we map them to their
205
* corresponding channel in batch and queue n-1 so that
206
* they can be handled by other handler threads. The last
207
* event is handled by this thread (and so is not queued).
208
*/
209
fdToChannelLock.readLock().lock();
210
try {
211
while (n-- > 0) {
212
long keventAddress = KQueue.getEvent(address, n);
213
int fd = KQueue.getDescriptor(keventAddress);
214
215
// wakeup
216
if (fd == sp[0]) {
217
if (wakeupCount.decrementAndGet() == 0) {
218
// consume one wakeup byte, never more as this
219
// would interfere with shutdown when there is
220
// a wakeup byte queued to wake each thread
221
int nread;
222
do {
223
nread = IOUtil.drain1(sp[0]);
224
} while (nread == IOStatus.INTERRUPTED);
225
}
226
227
// queue special event if there are more events
228
// to handle.
229
if (n > 0) {
230
queue.offer(EXECUTE_TASK_OR_SHUTDOWN);
231
continue;
232
}
233
return EXECUTE_TASK_OR_SHUTDOWN;
234
}
235
236
PollableChannel channel = fdToChannel.get(fd);
237
if (channel != null) {
238
int filter = KQueue.getFilter(keventAddress);
239
int events = 0;
240
if (filter == EVFILT_READ)
241
events = Net.POLLIN;
242
else if (filter == EVFILT_WRITE)
243
events = Net.POLLOUT;
244
245
Event ev = new Event(channel, events);
246
247
// n-1 events are queued; This thread handles
248
// the last one except for the wakeup
249
if (n > 0) {
250
queue.offer(ev);
251
} else {
252
return ev;
253
}
254
}
255
}
256
} finally {
257
fdToChannelLock.readLock().unlock();
258
}
259
}
260
} finally {
261
// to ensure that some thread will poll when all events have
262
// been consumed
263
queue.offer(NEED_TO_POLL);
264
}
265
}
266
267
public void run() {
268
Invoker.GroupAndInvokeCount myGroupAndInvokeCount =
269
Invoker.getGroupAndInvokeCount();
270
final boolean isPooledThread = (myGroupAndInvokeCount != null);
271
boolean replaceMe = false;
272
Event ev;
273
try {
274
for (;;) {
275
// reset invoke count
276
if (isPooledThread)
277
myGroupAndInvokeCount.resetInvokeCount();
278
279
try {
280
replaceMe = false;
281
ev = queue.take();
282
283
// no events and this thread has been "selected" to
284
// poll for more.
285
if (ev == NEED_TO_POLL) {
286
try {
287
ev = poll();
288
} catch (IOException x) {
289
x.printStackTrace();
290
return;
291
}
292
}
293
} catch (InterruptedException x) {
294
continue;
295
}
296
297
// handle wakeup to execute task or shutdown
298
if (ev == EXECUTE_TASK_OR_SHUTDOWN) {
299
Runnable task = pollTask();
300
if (task == null) {
301
// shutdown request
302
return;
303
}
304
// run task (may throw error/exception)
305
replaceMe = true;
306
task.run();
307
continue;
308
}
309
310
// process event
311
try {
312
ev.channel().onEvent(ev.events(), isPooledThread);
313
} catch (Error x) {
314
replaceMe = true; throw x;
315
} catch (RuntimeException x) {
316
replaceMe = true; throw x;
317
}
318
}
319
} finally {
320
// last handler to exit when shutdown releases resources
321
int remaining = threadExit(this, replaceMe);
322
if (remaining == 0 && isShutdown()) {
323
implClose();
324
}
325
}
326
}
327
}
328
}
329
330