use of java.nio.channels.SelectionKey in project openhab1-addons by openhab.
the class ConnectionManager method run.
/**
* Main method of the thread.
* Establishes new connections and waits for input data.
*/
@Override
public void run() {
final Object sync = new Object();
long lastCloseDetectTime = System.nanoTime();
while (!this.threadTreminate) {
long currTime = System.nanoTime();
try {
int timeoutMSec = DETECT_CLOSED_CHANNELS_INTERVAL_MSEC - (int) ((currTime - lastCloseDetectTime) / 1000000L);
if (timeoutMSec <= 0 || this.selector.select(timeoutMSec) == 0) {
// Detect closed channels
synchronized (sync) {
this.callback.runOnRefreshThreadAsync(new LcnBindingNotification() {
@Override
public void execute() {
for (Connection conn : ConnectionManager.this.connectionsById.values()) {
if (!conn.isChannelConnected() && !conn.isChannelConnecting()) {
logger.warn(String.format("Channel \"%s\" was closed unexpectedly (reconnecting...).", conn.getSets().getId()));
conn.beginReconnect(RECONNECT_INTERVAL_MSEC);
}
}
synchronized (sync) {
sync.notify();
}
}
});
sync.wait();
}
lastCloseDetectTime = currTime;
} else {
// Process selected keys (connect or read events)
Iterator<SelectionKey> iter = this.selector.selectedKeys().iterator();
while (iter.hasNext()) {
final SelectionKey key = iter.next();
// The invocation is done sync. to keep the SelectionKey valid
synchronized (sync) {
this.callback.runOnRefreshThreadAsync(new LcnBindingNotification() {
@Override
public void execute() {
Connection conn = (Connection) key.attachment();
try {
if (key.isConnectable()) {
conn.finishConnect();
} else if (key.isReadable()) {
conn.readAndProcess();
}
} catch (IOException ex) {
logger.warn(String.format("Cannot process channel \"%s\" (reconnecting...): %s", conn.getSets().getId(), ex.getMessage()));
conn.beginReconnect(RECONNECT_INTERVAL_MSEC);
}
synchronized (sync) {
sync.notify();
}
}
});
sync.wait();
}
iter.remove();
}
}
synchronized (this.channelRegisterSync) {
}
// Force a wait here if a new channel is registering
} catch (InterruptedException ex) {
} catch (IOException ex) {
logger.error("Selection failure: " + ex.getMessage());
}
}
}
use of java.nio.channels.SelectionKey in project XobotOS by xamarin.
the class SelectorImpl method doCancel.
/**
* Removes cancelled keys from the key set and selected key set, and
* deregisters the corresponding channels. Returns the number of keys
* removed from the selected key set.
*/
private int doCancel() {
int deselected = 0;
Set<SelectionKey> cancelledKeys = cancelledKeys();
synchronized (cancelledKeys) {
if (cancelledKeys.size() > 0) {
for (SelectionKey currentKey : cancelledKeys) {
mutableKeys.remove(currentKey);
deregister((AbstractSelectionKey) currentKey);
if (mutableSelectedKeys.remove(currentKey)) {
deselected++;
}
}
cancelledKeys.clear();
}
}
return deselected;
}
use of java.nio.channels.SelectionKey in project voltdb by VoltDB.
the class VoltNetwork method registerChannel.
/**
* Register a channel with the selector and create a Connection that will pass incoming events
* to the provided handler.
* @param channel
* @param handler
* @throws IOException
*/
Connection registerChannel(final SocketChannel channel, final InputHandler handler, final int interestOps, final ReverseDNSPolicy dns, final CipherExecutor cipherService, final SSLEngine sslEngine) throws IOException {
synchronized (channel.blockingLock()) {
channel.configureBlocking(false);
channel.socket().setKeepAlive(true);
}
Callable<Connection> registerTask = new Callable<Connection>() {
@Override
public Connection call() throws Exception {
final VoltPort port = VoltPortFactory.createVoltPort(channel, VoltNetwork.this, handler, (InetSocketAddress) channel.socket().getRemoteSocketAddress(), m_pool, cipherService, sslEngine);
port.registering();
/*
* This means we are used by a client. No need to wait then, trigger
* the reverse DNS lookup now.
*/
if (dns != ReverseDNSPolicy.NONE) {
port.resolveHostname(dns == ReverseDNSPolicy.SYNCHRONOUS);
}
try {
SelectionKey key = channel.register(m_selector, interestOps, null);
port.setKey(key);
port.registered();
//Fix a bug witnessed on the mini where the registration lock and the selector wakeup contained
//within was not enough to prevent the selector from returning the port after it was registered,
//but before setKey was called. Suspect a bug in the selector.wakeup() or register() implementation
//on the mac.
//The null check in invokeCallbacks will catch the null attachment, continue, and do the work
//next time through the selection loop
key.attach(port);
return port;
} finally {
m_ports.add(port);
m_numPorts.incrementAndGet();
}
}
};
FutureTask<Connection> ft = new FutureTask<Connection>(registerTask);
m_tasks.offer(ft);
m_selector.wakeup();
try {
return ft.get();
} catch (Exception e) {
throw new IOException(e);
}
}
use of java.nio.channels.SelectionKey in project voltdb by VoltDB.
the class SocketJoiner method runPrimary.
/*
* After startup everything is a primary and can accept
* new nodes into the cluster. This loop accepts the new socket
* and passes it off the HostMessenger via the JoinHandler interface
*/
private void runPrimary() throws Exception {
try {
// start the server socket on the right interface
doBind();
while (true) {
try {
final int selectedKeyCount = m_selector.select();
if (selectedKeyCount == 0)
continue;
Set<SelectionKey> selectedKeys = m_selector.selectedKeys();
try {
for (SelectionKey key : selectedKeys) {
processSSC((ServerSocketChannel) key.channel());
}
} finally {
selectedKeys.clear();
}
} catch (ClosedByInterruptException e) {
throw new InterruptedException();
} catch (ClosedSelectorException e) {
throw new InterruptedException();
} catch (Exception e) {
LOG.error("fault occurrent in the connection accept loop", e);
}
}
} finally {
for (ServerSocketChannel ssc : m_listenerSockets) {
try {
ssc.close();
} catch (IOException e) {
}
}
m_listenerSockets.clear();
try {
m_selector.close();
} catch (IOException e) {
}
m_selector = null;
}
}
use of java.nio.channels.SelectionKey in project voltdb by VoltDB.
the class VoltNetwork method resumeSelection.
private void resumeSelection(VoltPort port) {
SelectionKey key = port.getKey();
if (key.isValid()) {
key.interestOps(port.interestOps());
} else {
m_ports.remove(port);
m_numPorts.decrementAndGet();
}
}
Aggregations