blob: 4f3220d601ded12a855896632039b68aa58f49d5 [file] [log] [blame]
Thomas Vachuska24c849c2014-10-27 09:53:05 -07001/*
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07002 * Copyright 2014 Open Networking Laboratory
Thomas Vachuska24c849c2014-10-27 09:53:05 -07003 *
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07004 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
Thomas Vachuska24c849c2014-10-27 09:53:05 -07007 *
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07008 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
Thomas Vachuska24c849c2014-10-27 09:53:05 -070015 */
tom6a62aa22014-09-25 09:10:12 -070016package org.onlab.nio;
17
18import org.slf4j.Logger;
19import org.slf4j.LoggerFactory;
20
21import java.io.IOException;
22import java.nio.channels.Selector;
23
24import static com.google.common.base.Preconditions.checkArgument;
tom74d49652014-09-25 23:48:46 -070025import static java.lang.System.currentTimeMillis;
tom6a62aa22014-09-25 09:10:12 -070026
27/**
28 * Abstraction of an I/O processing loop based on an NIO selector.
29 */
30public abstract class SelectorLoop implements Runnable {
31
32 protected final Logger log = LoggerFactory.getLogger(getClass());
33
34 /**
35 * Selector used by this loop to pace the I/O operations.
36 */
37 protected final Selector selector;
38
39 /**
40 * Selection operations timeout; specified in millis.
41 */
42 protected long selectTimeout;
43
44 /**
45 * Retains the error that caused the loop to exit prematurely.
46 */
47 private Throwable error;
48
49 // State indicator
50 private enum State { STARTING, STARTED, STOPPING, STOPPED };
51 private volatile State state = State.STOPPED;
52
53 /**
54 * Creates a new selector loop with the given selection timeout.
55 *
56 * @param selectTimeout selection timeout; specified in millis
57 * @throws IOException if the backing selector cannot be opened
58 */
59 public SelectorLoop(long selectTimeout) throws IOException {
60 checkArgument(selectTimeout > 0, "Timeout must be positive");
61 this.selectTimeout = selectTimeout;
62 this.selector = openSelector();
63 }
64
65 /**
66 * Opens a new selector for the use by the loop.
67 *
68 * @return newly open selector
69 * @throws IOException if the backing selector cannot be opened
70 */
71 protected Selector openSelector() throws IOException {
72 return Selector.open();
73 }
74
75 /**
76 * Indicates that the loop is marked to run.
77 */
78 protected boolean isRunning() {
79 return state == State.STARTED || state == State.STARTING;
80 }
81
82 /**
83 * Returns the error, if there was one, that caused the loop to terminate
84 * prematurely.
85 *
86 * @return error or null if there was none
87 */
88 public Throwable getError() {
89 return error;
90 }
91
92 /**
93 * Contains the body of the I/O selector loop.
94 *
95 * @throws IOException if an error is encountered while selecting I/O
96 */
97 protected abstract void loop() throws IOException;
98
99 @Override
100 public void run() {
101 error = null;
102 state = State.STARTING;
103 try {
104 loop();
105 } catch (Throwable e) {
106 error = e;
107 log.error("Loop aborted", e);
108 }
109 notifyDone();
110 }
111
112 /**
113 * Notifies observers waiting for loop to become ready.
114 */
115 protected synchronized void notifyReady() {
116 state = State.STARTED;
117 notifyAll();
118 }
119
120 /**
121 * Triggers loop shutdown.
122 */
123 public void shutdown() {
124 // Mark the loop as no longer running and wake up the selector.
125 state = State.STOPPING;
126 selector.wakeup();
127 }
128
129 /**
130 * Notifies observers waiting for loop to fully stop.
131 */
132 private synchronized void notifyDone() {
133 state = State.STOPPED;
134 notifyAll();
135 }
136
tom74d49652014-09-25 23:48:46 -0700137 /**
138 * Waits for the loop execution to start.
139 *
140 * @param timeout number of milliseconds to wait
141 * @return true if loop started in time
142 */
143 public final synchronized boolean awaitStart(long timeout) {
144 long max = currentTimeMillis() + timeout;
145 while (state != State.STARTED && (currentTimeMillis() < max)) {
146 try {
147 wait(timeout);
148 } catch (InterruptedException e) {
149 throw new RuntimeException("Interrupted", e);
150 }
151 }
152 return state == State.STARTED;
153 }
154
155 /**
156 * Waits for the loop execution to stop.
157 *
158 * @param timeout number of milliseconds to wait
159 * @return true if loop finished in time
160 */
161 public final synchronized boolean awaitStop(long timeout) {
162 long max = currentTimeMillis() + timeout;
163 while (state != State.STOPPED && (currentTimeMillis() < max)) {
164 try {
165 wait(timeout);
166 } catch (InterruptedException e) {
167 throw new RuntimeException("Interrupted", e);
168 }
169 }
170 return state == State.STOPPED;
171 }
172
173
tom6a62aa22014-09-25 09:10:12 -0700174}