use of java.nio.channels.Selector in project tomcat by apache.
the class NioReceiver method listen.
/**
* Get data from channel and store in byte array
* send it to cluster
* @throws IOException IO error
*/
protected void listen() throws Exception {
if (doListen()) {
log.warn(sm.getString("nioReceiver.alreadyStarted"));
return;
}
setListen(true);
// Avoid NPEs if selector is set to null on stop.
Selector selector = this.selector.get();
if (selector != null && datagramChannel != null) {
//max size for a datagram packet
ObjectReader oreader = new ObjectReader(MAX_UDP_SIZE);
registerChannel(selector, datagramChannel, SelectionKey.OP_READ, oreader);
}
while (doListen() && selector != null) {
// selected set contains keys of the ready channels
try {
events();
socketTimeouts();
int n = selector.select(getSelectorTimeout());
if (n == 0) {
// nothing to do
continue;
}
// get an iterator over the set of selected keys
Iterator<SelectionKey> it = selector.selectedKeys().iterator();
// look at each key in the selected set
while (it != null && it.hasNext()) {
SelectionKey key = it.next();
// Is a new connection coming in?
if (key.isAcceptable()) {
ServerSocketChannel server = (ServerSocketChannel) key.channel();
SocketChannel channel = server.accept();
channel.socket().setReceiveBufferSize(getTxBufSize());
channel.socket().setSendBufferSize(getTxBufSize());
channel.socket().setTcpNoDelay(getTcpNoDelay());
channel.socket().setKeepAlive(getSoKeepAlive());
channel.socket().setOOBInline(getOoBInline());
channel.socket().setReuseAddress(getSoReuseAddress());
channel.socket().setSoLinger(getSoLingerOn(), getSoLingerTime());
channel.socket().setSoTimeout(getTimeout());
Object attach = new ObjectReader(channel);
registerChannel(selector, channel, SelectionKey.OP_READ, attach);
}
// is there data to read on this channel?
if (key.isReadable()) {
readDataFromSocket(key);
} else {
key.interestOps(key.interestOps() & (~SelectionKey.OP_WRITE));
}
// remove key from selected set, it's been handled
it.remove();
}
} catch (java.nio.channels.ClosedSelectorException cse) {
// ignore is normal at shutdown or stop listen socket
} catch (java.nio.channels.CancelledKeyException nx) {
log.warn(sm.getString("nioReceiver.clientDisconnect"));
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
log.error(sm.getString("nioReceiver.requestError"), t);
}
}
serverChannel.close();
if (datagramChannel != null) {
try {
datagramChannel.close();
} catch (Exception iox) {
if (log.isDebugEnabled())
log.debug("Unable to close datagram channel.", iox);
}
datagramChannel = null;
}
closeSelector();
}
use of java.nio.channels.Selector in project tomcat by apache.
the class NioChannel method getAttachment.
public Object getAttachment() {
Poller pol = getPoller();
Selector sel = pol != null ? pol.getSelector() : null;
SelectionKey key = sel != null ? getIOChannel().keyFor(sel) : null;
Object att = key != null ? key.attachment() : null;
return att;
}
use of java.nio.channels.Selector in project hs4j by killme2008.
the class NioTCPSession method blockingWrite.
/**
* Blocking write using temp selector
*
* @param channel
* @param message
* @param writeBuffer
* @return
* @throws IOException
* @throws ClosedChannelException
*/
protected final Object blockingWrite(SelectableChannel channel, WriteMessage message, IoBuffer writeBuffer) throws IOException, ClosedChannelException {
SelectionKey tmpKey = null;
Selector writeSelector = null;
int attempts = 0;
int bytesProduced = 0;
try {
while (writeBuffer.hasRemaining()) {
long len = doRealWrite(channel, writeBuffer);
if (len > 0) {
attempts = 0;
bytesProduced += len;
statistics.statisticsWrite(len);
} else {
attempts++;
if (writeSelector == null) {
writeSelector = SelectorFactory.getSelector();
if (writeSelector == null) {
// Continue using the main one.
continue;
}
tmpKey = channel.register(writeSelector, SelectionKey.OP_WRITE);
}
if (writeSelector.select(1000) == 0) {
if (attempts > 2) {
throw new IOException("Client disconnected");
}
}
}
}
if (!writeBuffer.hasRemaining() && message.getWriteFuture() != null) {
message.getWriteFuture().setResult(Boolean.TRUE);
}
} finally {
if (tmpKey != null) {
tmpKey.cancel();
tmpKey = null;
}
if (writeSelector != null) {
// Cancel the key.
writeSelector.selectNow();
SelectorFactory.returnSelector(writeSelector);
}
}
scheduleWritenBytes.addAndGet(0 - bytesProduced);
return message.getMessage();
}
use of java.nio.channels.Selector in project hs4j by killme2008.
the class Reactor method unregisterChannel.
final void unregisterChannel(SelectableChannel channel) throws IOException {
Selector selector = this.selector;
if (selector != null) {
if (channel != null) {
SelectionKey key = channel.keyFor(selector);
if (key != null) {
key.cancel();
}
}
}
wakeup();
}
use of java.nio.channels.Selector in project hs4j by killme2008.
the class Reactor method lookJVMBug.
/**
* Look jvm bug
*
* @param before
* @param selected
* @param wait
* @return
* @throws IOException
*/
private boolean lookJVMBug(long before, int selected, long wait) throws IOException {
boolean seeing = false;
long now = System.currentTimeMillis();
if (JVMBUG_THRESHHOLD > 0 && selected == 0 && wait > JVMBUG_THRESHHOLD && now - before < wait / 4 && !wakenUp.get() && /* waken up */
!Thread.currentThread().isInterrupted()) /* Interrupted */
{
jvmBug.incrementAndGet();
if (jvmBug.get() >= JVMBUG_THRESHHOLD2) {
gate.lock();
try {
lastJVMBug = now;
log.warn("JVM bug occured at " + new Date(lastJVMBug) + ",http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6403933,reactIndex=" + reactorIndex);
if (jvmBug1) {
log.debug("seeing JVM BUG(s) - recreating selector,reactIndex=" + reactorIndex);
} else {
jvmBug1 = true;
log.info("seeing JVM BUG(s) - recreating selector,reactIndex=" + reactorIndex);
}
seeing = true;
final Selector new_selector = SystemUtils.openSelector();
for (SelectionKey k : selector.keys()) {
if (!k.isValid() || k.interestOps() == 0) {
continue;
}
final SelectableChannel channel = k.channel();
final Object attachment = k.attachment();
channel.register(new_selector, k.interestOps(), attachment);
}
selector.close();
selector = new_selector;
} finally {
gate.unlock();
}
jvmBug.set(0);
} else if (jvmBug.get() == JVMBUG_THRESHHOLD || jvmBug.get() == JVMBUG_THRESHHOLD1) {
if (jvmBug0) {
log.debug("seeing JVM BUG(s) - cancelling interestOps==0,reactIndex=" + reactorIndex);
} else {
jvmBug0 = true;
log.info("seeing JVM BUG(s) - cancelling interestOps==0,reactIndex=" + reactorIndex);
}
gate.lock();
seeing = true;
try {
for (SelectionKey k : selector.keys()) {
if (k.isValid() && k.interestOps() == 0) {
k.cancel();
}
}
} finally {
gate.unlock();
}
}
} else {
jvmBug.set(0);
}
return seeing;
}
Aggregations