1 /*
2  * JBoss, Home of Professional Open Source
3  *
4  * Copyright 2013 Red Hat, Inc. and/or its affiliates.
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *     http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  */

18
19 package org.xnio.nio;
20
21 import java.nio.channels.CancelledKeyException;
22 import java.nio.channels.SelectionKey;
23
24 import static org.xnio.Bits.allAreClear;
25 import static org.xnio.Bits.allAreSet;
26
27 /**
28  * @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a>
29  */

30 abstract class NioHandle {
31     private final WorkerThread workerThread;
32     private final SelectionKey selectionKey;
33
34     protected NioHandle(final WorkerThread workerThread, final SelectionKey selectionKey) {
35         this.workerThread = workerThread;
36         this.selectionKey = selectionKey;
37     }
38
39     void resume(final int ops) {
40         try {
41             if (! allAreSet(selectionKey.interestOps(), ops)) {
42                 workerThread.setOps(selectionKey, ops);
43             }
44         } catch (CancelledKeyException ignored) {}
45     }
46
47     void wakeup(final int ops) {
48         workerThread.queueTask(new Runnable() {
49             public void run() {
50                 handleReady(ops);
51             }
52         });
53         try {
54             if (! allAreSet(selectionKey.interestOps(), ops)) {
55                 workerThread.setOps(selectionKey, ops);
56             }
57         } catch (CancelledKeyException ignored) {}
58     }
59
60     void suspend(final int ops) {
61         try {
62             if (! allAreClear(selectionKey.interestOps(), ops)) {
63                 workerThread.clearOps(selectionKey, ops);
64             }
65         } catch (CancelledKeyException ignored) {}
66     }
67
68     boolean isResumed(final int ops) {
69         try {
70             return allAreSet(selectionKey.interestOps(), ops);
71         } catch (CancelledKeyException ignored) {
72             return false;
73         }
74     }
75
76     abstract void handleReady(final int ops);
77
78     abstract void forceTermination();
79
80     abstract void terminated();
81
82     WorkerThread getWorkerThread() {
83         return workerThread;
84     }
85
86     SelectionKey getSelectionKey() {
87         return selectionKey;
88     }
89
90     void cancelKey(final boolean block) {
91         workerThread.cancelKey(selectionKey, block);
92     }
93 }
94