use of java.nio.channels.ClosedSelectorException in project Mindroid.java by Himmele.
the class SocketExecutor method run.
protected void run() {
while (!Thread.currentThread().isInterrupted() && mSelector.isOpen()) {
Set<SelectionKey> keys;
try {
Iterator<SelectableSocket> socketIterator = mSockets.iterator();
while (socketIterator.hasNext()) {
SelectableSocket socket = socketIterator.next();
if (socket.isOpen()) {
try {
socket.register(mSelector).attach(socket);
} catch (CancelledKeyException | ClosedChannelException ignore) {
}
}
}
mSelector.select();
keys = mSelector.selectedKeys();
} catch (IOException e) {
Log.e(LOG_TAG, e.getMessage(), e);
break;
} catch (ClosedSelectorException e) {
break;
}
Iterator<SelectionKey> itr = keys.iterator();
while (itr.hasNext()) {
SelectionKey key = itr.next();
itr.remove();
if (!key.isValid()) {
continue;
}
try {
SelectableSocket socket = (SelectableSocket) key.attachment();
if (key.isAcceptable()) {
socket.onOperation(SelectionKey.OP_ACCEPT);
}
if (key.isConnectable()) {
socket.onOperation(SelectionKey.OP_CONNECT);
}
if (key.isReadable()) {
socket.onOperation(SelectionKey.OP_READ);
}
if (key.isWritable()) {
socket.onOperation(SelectionKey.OP_WRITE);
}
} catch (CancelledKeyException ignore) {
}
}
}
for (SelectableSocket socket : mSockets) {
try {
socket.close();
} catch (IOException ignore) {
}
}
mSockets.clear();
}
use of java.nio.channels.ClosedSelectorException in project rxlib by RockyLOMO.
the class SocketHandlerBase method run.
@Override
public void run() {
while (true) {
try {
synchronized (_pendingRequest) {
Iterator changes = _pendingRequest.iterator();
while (changes.hasNext()) {
ChangeRequest change = (ChangeRequest) changes.next();
if (!processPendingRequest(change))
break;
changes.remove();
}
}
// wait events from selected channels
_selector.select();
Iterator selectedKeys = _selector.selectedKeys().iterator();
while (selectedKeys.hasNext()) {
SelectionKey key = (SelectionKey) selectedKeys.next();
selectedKeys.remove();
if (!key.isValid()) {
continue;
}
processSelect(key);
}
} catch (ClosedSelectorException e) {
break;
} catch (Exception e) {
logger.warning(Util.getErrorMessage(e));
}
}
logger.fine(this.getClass().getName() + " Closed.");
}
use of java.nio.channels.ClosedSelectorException in project spring-integration by spring-projects.
the class TcpNioClientConnectionFactory method run.
@Override
public void run() {
if (logger.isDebugEnabled()) {
logger.debug("Read selector running for connections to " + this.getHost() + ":" + this.getPort());
}
try {
this.selector = Selector.open();
while (this.isActive()) {
SocketChannel newChannel;
int soTimeout = this.getSoTimeout();
int selectionCount = 0;
try {
long timeout = soTimeout < 0 ? 0 : soTimeout;
if (getDelayedReads().size() > 0 && (timeout == 0 || getReadDelay() < timeout)) {
timeout = getReadDelay();
}
selectionCount = this.selector.select(timeout);
} catch (CancelledKeyException cke) {
if (logger.isDebugEnabled()) {
logger.debug("CancelledKeyException during Selector.select()");
}
}
while ((newChannel = this.newChannels.poll()) != null) {
try {
newChannel.register(this.selector, SelectionKey.OP_READ, this.channelMap.get(newChannel));
} catch (ClosedChannelException cce) {
if (logger.isDebugEnabled()) {
logger.debug("Channel closed before registering with selector for reading");
}
}
}
this.processNioSelections(selectionCount, this.selector, null, this.channelMap);
}
} catch (ClosedSelectorException cse) {
if (this.isActive()) {
logger.error("Selector closed", cse);
}
} catch (Exception e) {
logger.error("Exception in read selector thread", e);
this.setActive(false);
}
if (logger.isDebugEnabled()) {
logger.debug("Read selector exiting for connections to " + this.getHost() + ":" + this.getPort());
}
}
use of java.nio.channels.ClosedSelectorException in project i2p.i2p by i2p.
the class EventPumper method run.
/**
* The selector loop.
* On high-bandwidth routers, this is the thread with the highest CPU usage, so
* take care to minimize overhead and unnecessary debugging stuff.
*/
public void run() {
int loopCount = 0;
long lastFailsafeIteration = System.currentTimeMillis();
long lastBlockedIPClear = lastFailsafeIteration;
while (_alive && _selector.isOpen()) {
try {
loopCount++;
runDelayedEvents();
try {
// if (_log.shouldLog(Log.DEBUG))
// _log.debug("before select...");
int count = _selector.select(SELECTOR_LOOP_DELAY);
if (count > 0) {
// if (_log.shouldLog(Log.DEBUG))
// _log.debug("select returned " + count);
Set<SelectionKey> selected = _selector.selectedKeys();
// _context.statManager().addRateData("ntcp.pumperKeysPerLoop", selected.size());
processKeys(selected);
// does clear() do anything useful?
selected.clear();
}
} catch (ClosedSelectorException cse) {
continue;
} catch (IOException ioe) {
if (_log.shouldLog(Log.WARN))
_log.warn("Error selecting", ioe);
} catch (CancelledKeyException cke) {
if (_log.shouldLog(Log.WARN))
_log.warn("Error selecting", cke);
continue;
}
long now = System.currentTimeMillis();
if (lastFailsafeIteration + FAILSAFE_ITERATION_FREQ < now) {
// in the *cough* unthinkable possibility that there are bugs in
// the code, lets periodically pass over all NTCP connections and
// make sure that anything which should be able to write has been
// properly marked as such, etc
lastFailsafeIteration = now;
try {
Set<SelectionKey> all = _selector.keys();
_context.statManager().addRateData("ntcp.pumperKeySetSize", all.size());
_context.statManager().addRateData("ntcp.pumperLoopsPerSecond", loopCount / (FAILSAFE_ITERATION_FREQ / 1000));
loopCount = 0;
int failsafeWrites = 0;
int failsafeCloses = 0;
int failsafeInvalid = 0;
// Increase allowed idle time if we are well under allowed connections, otherwise decrease
boolean haveCap = _transport.haveCapacity(33);
if (haveCap)
_expireIdleWriteTime = Math.min(_expireIdleWriteTime + 1000, MAX_EXPIRE_IDLE_TIME);
else
_expireIdleWriteTime = Math.max(_expireIdleWriteTime - 3000, MIN_EXPIRE_IDLE_TIME);
for (SelectionKey key : all) {
try {
Object att = key.attachment();
if (!(att instanceof NTCPConnection))
// to the next con
continue;
NTCPConnection con = (NTCPConnection) att;
/**
* 100% CPU bug
* http://forums.java.net/jive/thread.jspa?messageID=255525
* http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6595055
*
* The problem is around a channel that was originally registered with Selector for i/o gets
* closed on the server side (due to early client side exit). But the server side can know
* about such channel only when it does i/o (read/write) and thereby getting into an IO exception.
* In this case, (bug 6595055)there are times (erroneous) when server side (selector) did not
* know the channel is already closed (peer-reset), but continue to do the selection cycle on
* a key set whose associated channel is alreay closed or invalid. Hence, selector's slect(..)
* keep spinging with zero return without blocking for the timeout period.
*
* One fix is to have a provision in the application, to check if any of the Selector's keyset
* is having a closed channel/or invalid registration due to channel closure.
*/
if ((!key.isValid()) && (!((SocketChannel) key.channel()).isConnectionPending()) && con.getTimeSinceCreated() > 2 * NTCPTransport.ESTABLISH_TIMEOUT) {
if (_log.shouldLog(Log.INFO))
_log.info("Removing invalid key for " + con);
// this will cancel the key, and it will then be removed from the keyset
con.close();
failsafeInvalid++;
continue;
}
if ((!con.isWriteBufEmpty()) && ((key.interestOps() & SelectionKey.OP_WRITE) == 0)) {
// out the door asap.
if (_log.shouldLog(Log.INFO))
_log.info("Failsafe write for " + con);
key.interestOps(SelectionKey.OP_WRITE | key.interestOps());
failsafeWrites++;
}
final long expire;
if ((!haveCap || !con.isInbound()) && con.getMayDisconnect() && con.getMessagesReceived() <= 2 && con.getMessagesSent() <= 1) {
expire = MAY_DISCON_TIMEOUT;
if (_log.shouldInfo())
_log.info("Possible early disconnect for " + con);
} else {
expire = _expireIdleWriteTime;
}
if (con.getTimeSinceSend() > expire && con.getTimeSinceReceive() > expire) {
// we haven't sent or received anything in a really long time, so lets just close 'er up
con.close();
failsafeCloses++;
}
} catch (CancelledKeyException cke) {
// cancelled while updating the interest ops. ah well
}
}
if (failsafeWrites > 0)
_context.statManager().addRateData("ntcp.failsafeWrites", failsafeWrites);
if (failsafeCloses > 0)
_context.statManager().addRateData("ntcp.failsafeCloses", failsafeCloses);
if (failsafeInvalid > 0)
_context.statManager().addRateData("ntcp.failsafeInvalid", failsafeInvalid);
} catch (ClosedSelectorException cse) {
continue;
}
} else {
// another 100% CPU workaround
if ((loopCount % 512) == 511) {
if (_log.shouldLog(Log.INFO))
_log.info("EventPumper throttle " + loopCount + " loops in " + (now - lastFailsafeIteration) + " ms");
_context.statManager().addRateData("ntcp.failsafeThrottle", 1);
try {
Thread.sleep(25);
} catch (InterruptedException ie) {
}
}
}
if (lastBlockedIPClear + BLOCKED_IP_FREQ < now) {
_blockedIPs.clear();
lastBlockedIPClear = now;
}
// Clear the cache if the user changes the setting,
// so we can test the effect.
boolean newUseDirect = _context.getBooleanProperty(PROP_DIRECT);
if (_useDirect != newUseDirect) {
_useDirect = newUseDirect;
_bufCache.clear();
}
} catch (RuntimeException re) {
_log.error("Error in the event pumper", re);
}
}
try {
if (_selector.isOpen()) {
if (_log.shouldLog(Log.DEBUG))
_log.debug("Closing down the event pumper with selection keys remaining");
Set<SelectionKey> keys = _selector.keys();
for (SelectionKey key : keys) {
try {
Object att = key.attachment();
if (att instanceof ServerSocketChannel) {
ServerSocketChannel chan = (ServerSocketChannel) att;
chan.close();
key.cancel();
} else if (att instanceof NTCPConnection) {
NTCPConnection con = (NTCPConnection) att;
con.close();
key.cancel();
}
} catch (IOException ke) {
_log.error("Error closing key " + key + " on pumper shutdown", ke);
}
}
_selector.close();
} else {
if (_log.shouldLog(Log.DEBUG))
_log.debug("Closing down the event pumper with no selection keys remaining");
}
} catch (IOException e) {
_log.error("Error closing keys on pumper shutdown", e);
}
_wantsConRegister.clear();
_wantsRead.clear();
_wantsRegister.clear();
_wantsWrite.clear();
_bufCache.clear();
}
use of java.nio.channels.ClosedSelectorException in project cosmic by MissionCriticalCloud.
the class NioConnection method call.
@Override
public Boolean call() throws NioConnectionException {
while (_isRunning) {
try {
_selector.select();
// Someone is ready for I/O, get the ready keys
final Set<SelectionKey> readyKeys = _selector.selectedKeys();
final Iterator<SelectionKey> i = readyKeys.iterator();
if (s_logger.isTraceEnabled()) {
s_logger.trace("Keys Processing: " + readyKeys.size());
}
// Walk through the ready keys collection.
while (i.hasNext()) {
final SelectionKey sk = i.next();
i.remove();
if (!sk.isValid()) {
if (s_logger.isTraceEnabled()) {
s_logger.trace("Selection Key is invalid: " + sk.toString());
}
final Link link = (Link) sk.attachment();
if (link != null) {
link.terminated();
} else {
closeConnection(sk);
}
} else if (sk.isReadable()) {
read(sk);
} else if (sk.isWritable()) {
write(sk);
} else if (sk.isAcceptable()) {
accept(sk);
} else if (sk.isConnectable()) {
connect(sk);
}
}
s_logger.trace("Keys Done Processing.");
processTodos();
} catch (final ClosedSelectorException e) {
/*
* Exception occurred when calling java.nio.channels.Selector.selectedKeys() method. It means the connection has not yet been established. Let's continue trying
* We do not log it here otherwise we will fill the disk with messages.
*/
} catch (final IOException e) {
s_logger.error("Agent will die due to this IOException!", e);
throw new NioConnectionException(e.getMessage(), e);
}
}
_isStartup = false;
return true;
}
Aggregations