java.nio.channels.SelectableChannel Java Examples
The following examples show how to use
java.nio.channels.SelectableChannel.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: NetworkManager.java From attic-apex-malhar with Apache License 2.0 | 6 votes |
public synchronized void unregisterAction(ChannelAction action) throws IOException, InterruptedException { ChannelConfiguration channelConfiguration = action.channelConfiguration; SelectableChannel channel = channelConfiguration.channel; if (channelConfiguration != null) { channelConfiguration.actions.remove(action); if (channelConfiguration.actions.size() == 0) { ConnectionInfo connectionInfo = channelConfiguration.connectionInfo; channelConfigurations.remove(channel); channels.remove(connectionInfo); channel.close(); } } if (channels.size() == 0) { stopProcess(); } }
Example #2
Source File: NioEventLoop.java From netty-4.1.22 with Apache License 2.0 | 6 votes |
private static void processSelectedKey(SelectionKey k, NioTask<SelectableChannel> task) { int state = 0; try { task.channelReady(k.channel(), k); state = 1; } catch (Exception e) { k.cancel(); invokeChannelUnregistered(task, k, e); state = 2; } finally { switch (state) { case 0: k.cancel(); invokeChannelUnregistered(task, k, null); break; case 1: if (!k.isValid()) { // Cancelled by channelReady() invokeChannelUnregistered(task, k, null); } break; } } }
Example #3
Source File: NioEventLoop.java From netty-4.1.22 with Apache License 2.0 | 6 votes |
private void closeAll() { // 立即事件监听 selectAgain(); Set<SelectionKey> keys = selector.keys(); Collection<AbstractNioChannel> channels = new ArrayList<AbstractNioChannel>(keys.size()); for (SelectionKey k: keys) { Object a = k.attachment(); if (a instanceof AbstractNioChannel) { // 如果是netty的channel添加到集合 channels.add((AbstractNioChannel) a); } else { // 负责取消selectionKey k.cancel(); @SuppressWarnings("unchecked") NioTask<SelectableChannel> task = (NioTask<SelectableChannel>) a; // 执行NioTask的channel取消注册事件 invokeChannelUnregistered(task, k, null); } } // 关闭channel for (AbstractNioChannel ch: channels) { ch.unsafe().close(ch.unsafe().voidPromise()); } }
Example #4
Source File: NioProcessor.java From craft-atom with MIT License | 6 votes |
private boolean isBrokenConnection() throws IOException { boolean broken = false; synchronized (selector) { Set<SelectionKey> keys = selector.keys(); for (SelectionKey key : keys) { SelectableChannel channel = key.channel(); if (!((SocketChannel) channel).isConnected()) { // The channel is not connected anymore. Cancel the associated key. key.cancel(); broken = true; } } } return broken; }
Example #5
Source File: AbstractSelectableChannelTest.java From j2objc with Apache License 2.0 | 6 votes |
/** * @tests AbstractSelectableChannel#configureBlocking(boolean) */ public void test_configureBlocking_Z_IllegalBlockingMode() throws Exception { SocketChannel sc = SocketChannel.open(); sc.configureBlocking(false); Selector acceptSelector = SelectorProvider.provider().openSelector(); SelectionKey acceptKey = sc.register(acceptSelector, SelectionKey.OP_READ, null); assertEquals(sc.keyFor(acceptSelector), acceptKey); SelectableChannel getChannel = sc.configureBlocking(false); assertEquals(getChannel, sc); try { sc.configureBlocking(true); fail("Should throw IllegalBlockingModeException"); } catch (IllegalBlockingModeException e) { // expected } }
Example #6
Source File: AbstractSelectableChannel.java From dragonwell8_jdk with GNU General Public License v2.0 | 6 votes |
/** * Adjusts this channel's blocking mode. * * <p> If the given blocking mode is different from the current blocking * mode then this method invokes the {@link #implConfigureBlocking * implConfigureBlocking} method, while holding the appropriate locks, in * order to change the mode. </p> */ public final SelectableChannel configureBlocking(boolean block) throws IOException { synchronized (regLock) { if (!isOpen()) throw new ClosedChannelException(); boolean blocking = !nonBlocking; if (block != blocking) { if (block && haveValidKeys()) throw new IllegalBlockingModeException(); implConfigureBlocking(block); nonBlocking = !block; } } return this; }
Example #7
Source File: SocketIOWithTimeout.java From RDFS with Apache License 2.0 | 6 votes |
private static String timeoutExceptionString(SelectableChannel channel, long timeout, int ops) { String waitingFor; switch(ops) { case SelectionKey.OP_READ : waitingFor = "read"; break; case SelectionKey.OP_WRITE : waitingFor = "write"; break; case SelectionKey.OP_CONNECT : waitingFor = "connect"; break; default : waitingFor = "" + ops; } return timeout + " millis timeout while " + "waiting for channel to be ready for " + waitingFor + ". ch : " + channel; }
Example #8
Source File: Reactor.java From TarsJava with BSD 3-Clause "New" or "Revised" License | 6 votes |
public void registerChannel(SelectableChannel channel, int ops, Object attachment) throws IOException { if (crashed) { throw new IOException("The reactor thread crashed.... "); } if (Thread.currentThread() == this) { SelectionKey key = channel.register(this.selector, ops, attachment); if (attachment instanceof TCPSession) { ((TCPSession) attachment).setKey(key); } } else { this.register.offer(new Object[] { channel, ops, attachment }); this.selector.wakeup(); } }
Example #9
Source File: SelectorTest.java From incubator-tuweni with Apache License 2.0 | 6 votes |
@Test void selectorRemovesKeysOnCancelWhenSelecting() throws Exception { Pipe pipe = Pipe.open(); Selector selector = Selector.open(); SelectableChannel source = pipe.source(); source.configureBlocking(false); SelectionKey key = source.register(selector, OP_READ); assertTrue(selector.keys().contains(key)); key.cancel(); assertTrue(selector.keys().contains(key)); assertSame(key, source.keyFor(selector)); selector.selectNow(); assertFalse(selector.keys().contains(key)); assertNull(source.keyFor(selector)); }
Example #10
Source File: NIOConnectionManager.java From bt with Apache License 2.0 | 6 votes |
void connectionChecks() throws IOException { if((iterations & 0x0F) != 0) return; long now = System.currentTimeMillis(); if(now - lastConnectionCheck < 500) return; lastConnectionCheck = now; for(Selectable conn : new ArrayList<>(connections)) { conn.doStateChecks(now); SelectableChannel ch = conn.getChannel(); SelectionKey k; if(ch == null || (k = ch.keyFor(selector)) == null || !k.isValid()) connections.remove(conn); } }
Example #11
Source File: WebSocketServer.java From Slyther with MIT License | 6 votes |
private void handleIOException( SelectionKey key, WebSocket conn, IOException ex ) { // onWebsocketError( conn, ex );// conn may be null here if( conn != null ) { conn.closeConnection( CloseFrame.ABNORMAL_CLOSE, ex.getMessage() ); } else if( key != null ) { SelectableChannel channel = key.channel(); if( channel != null && channel.isOpen() ) { // this could be the case if the IOException ex is a SSLException try { channel.close(); } catch ( IOException e ) { // there is nothing that must be done here } if( WebSocketImpl.DEBUG ) System.out.println( "Connection closed because of" + ex ); } } }
Example #12
Source File: SelectorImpl.java From hottub with GNU General Public License v2.0 | 5 votes |
private void clearDeferredRegistrations() { synchronized (deferredRegistrations) { int deferredListSize = deferredRegistrations.size(); if (orb.transportDebugFlag) { dprint(".clearDeferredRegistrations:deferred list size == " + deferredListSize); } for (int i = 0; i < deferredListSize; i++) { EventHandler eventHandler = (EventHandler)deferredRegistrations.get(i); if (orb.transportDebugFlag) { dprint(".clearDeferredRegistrations: " + eventHandler); } SelectableChannel channel = eventHandler.getChannel(); SelectionKey selectionKey = null; try { if (orb.transportDebugFlag) { dprint(".clearDeferredRegistrations:close channel == " + channel); dprint(".clearDeferredRegistrations:close channel class == " + channel.getClass().getName()); } channel.close(); selectionKey = eventHandler.getSelectionKey(); if (selectionKey != null) { selectionKey.cancel(); selectionKey.attach(null); } } catch (IOException ioEx) { if (orb.transportDebugFlag) { dprint(".clearDeferredRegistrations: ", ioEx); } } } deferredRegistrations.clear(); } }
Example #13
Source File: HeronClient.java From incubator-heron with Apache License 2.0 | 5 votes |
@Override public void handleRead(SelectableChannel channel) { List<IncomingPacket> packets = socketChannelHelper.read(); for (IncomingPacket ipt : packets) { handlePacket(ipt); } }
Example #14
Source File: Server.java From twister2 with Apache License 2.0 | 5 votes |
@Override public void handleWrite(SelectableChannel ch) { BaseNetworkChannel channel = connectedChannels.get(ch); if (channel != null) { channel.write(); } else { LOG.warning("Un-expected channel ready for write"); } }
Example #15
Source File: SelectorManager.java From IoTgo_Android_App with MIT License | 5 votes |
public void addChange(SelectableChannel channel, Object att) { if (att==null) addChange(channel); else if (att instanceof EndPoint) addChange(att); else addChange(new ChannelAndAttachment(channel,att)); }
Example #16
Source File: ReactorEchoServerV1.java From new-bull with MIT License | 5 votes |
public void register(SelectableChannel channel, int ops, Handler handler) { try { channel.register(selector, ops, handler); } catch (ClosedChannelException e) { e.printStackTrace(); } }
Example #17
Source File: SelectorImpl.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
private void handleDeferredRegistrations() { synchronized (deferredRegistrations) { int deferredListSize = deferredRegistrations.size(); for (int i = 0; i < deferredListSize; i++) { EventHandler eventHandler = (EventHandler)deferredRegistrations.get(i); if (orb.transportDebugFlag) { dprint(".handleDeferredRegistrations: " + eventHandler); } SelectableChannel channel = eventHandler.getChannel(); SelectionKey selectionKey = null; try { selectionKey = channel.register(selector, eventHandler.getInterestOps(), (Object)eventHandler); } catch (ClosedChannelException e) { if (orb.transportDebugFlag) { dprint(".handleDeferredRegistrations: ", e); } } eventHandler.setSelectionKey(selectionKey); } deferredRegistrations.clear(); } }
Example #18
Source File: WindowsSelectorImpl.java From jdk8u-jdk with GNU General Public License v2.0 | 5 votes |
protected void implClose() throws IOException { synchronized (closeLock) { if (channelArray != null) { if (pollWrapper != null) { // prevent further wakeup synchronized (interruptLock) { interruptTriggered = true; } wakeupPipe.sink().close(); wakeupPipe.source().close(); for(int i = 1; i < totalChannels; i++) { // Deregister channels if (i % MAX_SELECTABLE_FDS != 0) { // skip wakeupEvent deregister(channelArray[i]); SelectableChannel selch = channelArray[i].channel(); if (!selch.isOpen() && !selch.isRegistered()) ((SelChImpl)selch).kill(); } } pollWrapper.free(); pollWrapper = null; selectedKeys = null; channelArray = null; // Make all remaining helper threads exit for (SelectThread t: threads) t.makeZombie(); startLock.startThreads(); } } } }
Example #19
Source File: Dispatcher.java From jReto with MIT License | 5 votes |
public Dispatcher(Executor executor) throws IOException { this.selector = Selector.open(); this.executor = executor; this.runnables = new LinkedBlockingQueue<Runnable>(); this.handlersByChannelByOperation = new ConcurrentHashMap<Integer, HashMap<SelectableChannel,HandlerDispatcher<?>>>(); for (int operation : ALL_OPERATIONS) this.handlersByChannelByOperation.put(operation, new HashMap<SelectableChannel, HandlerDispatcher<?>>()); }
Example #20
Source File: WindowsSelectorImpl.java From hottub with GNU General Public License v2.0 | 5 votes |
protected void implClose() throws IOException { synchronized (closeLock) { if (channelArray != null) { if (pollWrapper != null) { // prevent further wakeup synchronized (interruptLock) { interruptTriggered = true; } wakeupPipe.sink().close(); wakeupPipe.source().close(); for(int i = 1; i < totalChannels; i++) { // Deregister channels if (i % MAX_SELECTABLE_FDS != 0) { // skip wakeupEvent deregister(channelArray[i]); SelectableChannel selch = channelArray[i].channel(); if (!selch.isOpen() && !selch.isRegistered()) ((SelChImpl)selch).kill(); } } pollWrapper.free(); pollWrapper = null; selectedKeys = null; channelArray = null; // Make all remaining helper threads exit for (SelectThread t: threads) t.makeZombie(); startLock.startThreads(); } } } }
Example #21
Source File: WindowsSelectorImpl.java From jdk8u-dev-jdk with GNU General Public License v2.0 | 5 votes |
protected void implClose() throws IOException { synchronized (closeLock) { if (channelArray != null) { if (pollWrapper != null) { // prevent further wakeup synchronized (interruptLock) { interruptTriggered = true; } wakeupPipe.sink().close(); wakeupPipe.source().close(); for(int i = 1; i < totalChannels; i++) { // Deregister channels if (i % MAX_SELECTABLE_FDS != 0) { // skip wakeupEvent deregister(channelArray[i]); SelectableChannel selch = channelArray[i].channel(); if (!selch.isOpen() && !selch.isRegistered()) ((SelChImpl)selch).kill(); } } pollWrapper.free(); pollWrapper = null; selectedKeys = null; channelArray = null; // Make all remaining helper threads exit for (SelectThread t: threads) t.makeZombie(); startLock.startThreads(); } } } }
Example #22
Source File: WindowsSelectorImpl.java From openjdk-8 with GNU General Public License v2.0 | 5 votes |
protected void implClose() throws IOException { synchronized (closeLock) { if (channelArray != null) { if (pollWrapper != null) { // prevent further wakeup synchronized (interruptLock) { interruptTriggered = true; } wakeupPipe.sink().close(); wakeupPipe.source().close(); for(int i = 1; i < totalChannels; i++) { // Deregister channels if (i % MAX_SELECTABLE_FDS != 0) { // skip wakeupEvent deregister(channelArray[i]); SelectableChannel selch = channelArray[i].channel(); if (!selch.isOpen() && !selch.isRegistered()) ((SelChImpl)selch).kill(); } } pollWrapper.free(); pollWrapper = null; selectedKeys = null; channelArray = null; // Make all remaining helper threads exit for (SelectThread t: threads) t.makeZombie(); startLock.startThreads(); } } } }
Example #23
Source File: SocketIOWithTimeout.java From hadoop with Apache License 2.0 | 5 votes |
/** * Takes one selector from end of LRU list of free selectors. * If there are no selectors awailable, it creates a new selector. * Also invokes trimIdleSelectors(). * * @param channel * @return * @throws IOException */ private synchronized SelectorInfo get(SelectableChannel channel) throws IOException { SelectorInfo selInfo = null; SelectorProvider provider = channel.provider(); // pick the list : rarely there is more than one provider in use. ProviderInfo pList = providerList; while (pList != null && pList.provider != provider) { pList = pList.next; } if (pList == null) { //LOG.info("Creating new ProviderInfo : " + provider.toString()); pList = new ProviderInfo(); pList.provider = provider; pList.queue = new LinkedList<SelectorInfo>(); pList.next = providerList; providerList = pList; } LinkedList<SelectorInfo> queue = pList.queue; if (queue.isEmpty()) { Selector selector = provider.openSelector(); selInfo = new SelectorInfo(); selInfo.selector = selector; selInfo.queue = queue; } else { selInfo = queue.removeLast(); } trimIdleSelectors(Time.now()); return selInfo; }
Example #24
Source File: NioAcceptor.java From craft-atom with MIT License | 5 votes |
private void shutdown0() throws IOException { // clear bind/unbind addresses cache this.bindAddresses.clear(); this.unbindAddresses.clear(); // close all opened server socket channel for (SelectableChannel sc : boundmap.values()) { close(sc); } // close acceptor selector this.selector.close(); super.shutdown(); LOG.debug("[CRAFT-ATOM-NIO] Shutdown acceptor successful"); }
Example #25
Source File: NioAcceptor.java From craft-atom with MIT License | 5 votes |
/** * Rollback already bound address */ protected void rollback() { Iterator<Entry<SocketAddress, SelectableChannel>> it = boundmap.entrySet().iterator(); while(it.hasNext()) { Entry<SocketAddress, SelectableChannel> entry = it.next(); try { close(entry.getValue()); } catch (IOException e) { LOG.warn("[CRAFT-ATOM-NIO] Rollback bind operation exception", e); } finally { it.remove(); } } }
Example #26
Source File: TcpConnectorService.java From linstor-server with GNU General Public License v3.0 | 5 votes |
private void closeConnection(SelectionKey currentKey, boolean allowReconnect, boolean shuttingDown) { Peer client = (TcpConnectorPeer) currentKey.attachment(); if (client != null) { connObserver.connectionClosed(client, allowReconnect, shuttingDown); try { if (client.isConnected(false)) { client.connectionClosing(); } } catch (CancelledKeyException ignored) { // connectionClosing() calls interestOps on the selection Key, which may fail } } try { SelectableChannel channel = currentKey.channel(); if (channel != null) { channel.close(); } } catch (IOException closeIoExc) { // If close() fails with an I/O error, the reason may be interesting // enough to file an error report errorReporter.reportError(closeIoExc); } currentKey.cancel(); }
Example #27
Source File: WindowsSelectorImpl.java From openjdk-jdk8u with GNU General Public License v2.0 | 5 votes |
protected void implClose() throws IOException { synchronized (closeLock) { if (channelArray != null) { if (pollWrapper != null) { // prevent further wakeup synchronized (interruptLock) { interruptTriggered = true; } wakeupPipe.sink().close(); wakeupPipe.source().close(); for(int i = 1; i < totalChannels; i++) { // Deregister channels if (i % MAX_SELECTABLE_FDS != 0) { // skip wakeupEvent deregister(channelArray[i]); SelectableChannel selch = channelArray[i].channel(); if (!selch.isOpen() && !selch.isRegistered()) ((SelChImpl)selch).kill(); } } pollWrapper.free(); pollWrapper = null; selectedKeys = null; channelArray = null; // Make all remaining helper threads exit for (SelectThread t: threads) t.makeZombie(); startLock.startThreads(); subSelector.freeFDSetBuffer(); } } } }
Example #28
Source File: SocketIOWithTimeout.java From hadoop with Apache License 2.0 | 5 votes |
SocketIOWithTimeout(SelectableChannel channel, long timeout) throws IOException { checkChannelValidity(channel); this.channel = channel; this.timeout = timeout; // Set non-blocking channel.configureBlocking(false); }
Example #29
Source File: SelectorThread.java From AdditionsAPI with MIT License | 5 votes |
public SelectionKey register(SelectableChannel channel, Object attachment) throws ClosedChannelException { SelectionKey result; synchronized(this.registerLock) { this.selector.wakeup(); result = channel.register(this.selector, this.selectionHandler.getDefaultInterestSet(), attachment); } this.getSelectionHandler().onRegister(result); return result; }
Example #30
Source File: NioReceiver.java From Tomcat8-Source-Read with MIT License | 5 votes |
/** * Register the given channel with the given selector for * the given operations of interest * @param selector The selector to use * @param channel The channel * @param ops The operations to register * @param attach Attachment object * @throws Exception IO error with channel */ protected void registerChannel(Selector selector, SelectableChannel channel, int ops, Object attach) throws Exception { if (channel == null)return; // could happen // set the new channel non-blocking channel.configureBlocking(false); // register it with the selector channel.register(selector, ops, attach); }