1
18
19 package org.xnio.nio;
20
21 import static org.xnio.nio.Log.log;
22
23 import java.io.IOException;
24 import java.io.InterruptedIOException;
25 import java.nio.channels.ClosedChannelException;
26 import java.nio.channels.SelectableChannel;
27 import java.nio.channels.SelectionKey;
28 import java.nio.channels.Selector;
29 import java.util.concurrent.TimeUnit;
30
31 import org.xnio.Xnio;
32
33 final class SelectorUtils {
34 private SelectorUtils() {
35 }
36
37 public static void await(NioXnio nioXnio, SelectableChannel channel, int op) throws IOException {
38 if (NioXnio.IS_HP_UX) {
39
40 await(nioXnio, channel, op, 1, TimeUnit.SECONDS);
41 return;
42 }
43 Xnio.checkBlockingAllowed();
44 final Selector selector = nioXnio.getSelector();
45 final SelectionKey selectionKey;
46 try {
47 selectionKey = channel.register(selector, op);
48 } catch (ClosedChannelException e) {
49 return;
50 }
51 selector.select();
52 selector.selectedKeys().clear();
53 if (Thread.currentThread().isInterrupted()) {
54 throw log.interruptedIO();
55 }
56 selectionKey.cancel();
57 selector.selectNow();
58 }
59
60 public static void await(NioXnio nioXnio, SelectableChannel channel, int op, long time, TimeUnit unit) throws IOException {
61 if (time <= 0) {
62 await(nioXnio, channel, op);
63 return;
64 }
65 Xnio.checkBlockingAllowed();
66 final Selector selector = nioXnio.getSelector();
67 final SelectionKey selectionKey;
68 try {
69 selectionKey = channel.register(selector, op);
70 } catch (ClosedChannelException e) {
71 return;
72 }
73 long timeoutInMillis = unit.toMillis(time);
74 selector.select(timeoutInMillis == 0 ? 1: timeoutInMillis);
75 selector.selectedKeys().clear();
76 if (Thread.currentThread().isInterrupted()) {
77 throw log.interruptedIO();
78 }
79 selectionKey.cancel();
80 selector.selectNow();
81 }
82 }
83