java.nio.channels.Selector Java Examples
The following examples show how to use
java.nio.channels.Selector.
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: NIOAcceptor.java From Mycat-NIO with Apache License 2.0 | 6 votes |
@Override public void run() { final Selector selector = this.selector; for (;;) { ++acceptCount; try { selector.select(1000L); Set<SelectionKey> keys = selector.selectedKeys(); try { for (SelectionKey key : keys) { if (key.isValid() && key.isAcceptable()) { accept(); } else { key.cancel(); } } } finally { keys.clear(); } } catch (Throwable e) { LOGGER.warn(getName(), e); } } }
Example #2
Source File: WakeupSpeed.java From TencentKona-8 with GNU General Public License v2.0 | 6 votes |
public static void main(String argv[]) throws Exception { int waitTime = 4000; Selector selector = Selector.open(); try { selector.wakeup(); long t1 = System.currentTimeMillis(); selector.select(waitTime); long t2 = System.currentTimeMillis(); long totalTime = t2 - t1; if (totalTime > waitTime) throw new RuntimeException("Test failed"); } finally { selector.close(); } }
Example #3
Source File: SelectorThread.java From L2jBrasil with GNU General Public License v3.0 | 6 votes |
public SelectorThread(final SelectorConfig sc, final IMMOExecutor<T> executor, final IPacketHandler<T> packetHandler, final IClientFactory<T> clientFactory, final IAcceptFilter acceptFilter) throws IOException { super.setName("SelectorThread-" + super.getId()); HELPER_BUFFER_SIZE = sc.HELPER_BUFFER_SIZE; HELPER_BUFFER_COUNT = sc.HELPER_BUFFER_COUNT; MAX_SEND_PER_PASS = sc.MAX_SEND_PER_PASS; MAX_READ_PER_PASS = sc.MAX_READ_PER_PASS; SLEEP_TIME = sc.SLEEP_TIME; DIRECT_WRITE_BUFFER = ByteBuffer.allocateDirect(sc.WRITE_BUFFER_SIZE) .order(BYTE_ORDER); WRITE_BUFFER = ByteBuffer.wrap(new byte[sc.WRITE_BUFFER_SIZE]).order(BYTE_ORDER); READ_BUFFER = ByteBuffer.wrap(new byte[sc.READ_BUFFER_SIZE]).order(BYTE_ORDER); STRING_BUFFER = new NioNetStringBuffer(64 * 1024); _pendingClose = new NioNetStackList<MMOConnection<T>>(); _bufferPool = new ArrayList<>(); for (int i = 0; i < HELPER_BUFFER_COUNT; i++) _bufferPool.add(_bufferPool.size(), ByteBuffer.wrap(new byte[HELPER_BUFFER_SIZE]).order(BYTE_ORDER)); _acceptFilter = acceptFilter; _packetHandler = packetHandler; _clientFactory = clientFactory; _executor = executor; _selector = Selector.open(); }
Example #4
Source File: NioSelectorPool.java From tomcatsrc with Apache License 2.0 | 6 votes |
protected Selector getSharedSelector() throws IOException { if (SHARED && SHARED_SELECTOR == null) { synchronized ( NioSelectorPool.class ) { if ( SHARED_SELECTOR == null ) { synchronized (Selector.class) { // Selector.open() isn't thread safe // http://bugs.sun.com/view_bug.do?bug_id=6427854 // Affects 1.6.0_29, fixed in 1.7.0_01 SHARED_SELECTOR = Selector.open(); } log.info("Using a shared selector for servlet write/read"); } } } return SHARED_SELECTOR; }
Example #5
Source File: Common.java From aeron with Apache License 2.0 | 6 votes |
public static NioSelectedKeySet keySet(final Selector selector) { NioSelectedKeySet tmpSet = null; if (null != PUBLIC_SELECTED_KEYS_FIELD) { try { tmpSet = new NioSelectedKeySet(); SELECTED_KEYS_FIELD.set(selector, tmpSet); PUBLIC_SELECTED_KEYS_FIELD.set(selector, tmpSet); } catch (final Exception ignore) { tmpSet = null; } } return tmpSet; }
Example #6
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 #7
Source File: Server.java From hadoop-gpu with Apache License 2.0 | 6 votes |
public Listener() throws IOException { address = new InetSocketAddress(bindAddress, port); // Create a new server socket and set to non blocking mode acceptChannel = ServerSocketChannel.open(); acceptChannel.configureBlocking(false); // Bind the server socket to the local host and port bind(acceptChannel.socket(), address, backlogLength); port = acceptChannel.socket().getLocalPort(); //Could be an ephemeral port // create a selector; selector= Selector.open(); // Register accepts on the server socket with the selector. acceptChannel.register(selector, SelectionKey.OP_ACCEPT); this.setName("IPC Server listener on " + port); this.setDaemon(true); }
Example #8
Source File: WakeupAfterClose.java From jdk8u60 with GNU General Public License v2.0 | 6 votes |
public static void main(String[] args) throws Exception { final Selector sel = Selector.open(); Runnable r = new Runnable() { public void run() { try { sel.select(); } catch (IOException x) { x.printStackTrace(); } } }; // start thread to block in Selector Thread t = new Thread(r); t.start(); // give thread time to start Thread.sleep(1000); // interrupt, close, and wakeup is the magic sequence to provoke the NPE t.interrupt(); sel.close(); sel.wakeup(); }
Example #9
Source File: SelectorImpl.java From TencentKona-8 with GNU General Public License v2.0 | 6 votes |
private void startSelector() { try { selector = Selector.open(); } catch (IOException e) { if (orb.transportDebugFlag) { dprint(".startSelector: Selector.open: IOException: ", e); } // REVISIT - better handling/reporting RuntimeException rte = new RuntimeException(".startSelector: Selector.open exception"); rte.initCause(e); throw rte; } setDaemon(true); start(); selectorStarted = true; if (orb.transportDebugFlag) { dprint(".startSelector: selector.start completed."); } }
Example #10
Source File: AbstractNioWorker.java From android-netty with Apache License 2.0 | 6 votes |
protected void clearOpWrite(AbstractNioChannel<?> channel) { Selector selector = this.selector; SelectionKey key = channel.channel.keyFor(selector); if (key == null) { return; } if (!key.isValid()) { close(key); return; } int interestOps = channel.getRawInterestOps(); if ((interestOps & SelectionKey.OP_WRITE) != 0) { interestOps &= ~SelectionKey.OP_WRITE; key.interestOps(interestOps); channel.setRawInterestOpsNow(interestOps); } }
Example #11
Source File: SelectorTest.java From cava with Apache License 2.0 | 6 votes |
@Test void selectorRemovesKeysOnChannelCloseWhenSelecting() 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)); source.close(); assertTrue(selector.keys().contains(key)); selector.selectNow(); assertFalse(selector.keys().contains(key)); }
Example #12
Source File: NioSelectorPool.java From Tomcat7.0.67 with Apache License 2.0 | 5 votes |
public void put(Selector s) throws IOException { if ( SHARED ) return; if ( enabled ) active.decrementAndGet(); if ( enabled && (maxSpareSelectors==-1 || spare.get() < Math.min(maxSpareSelectors,maxSelectors)) ) { spare.incrementAndGet(); selectors.offer(s); } else s.close(); }
Example #13
Source File: NioEventLoopTest.java From netty-4.1.22 with Apache License 2.0 | 5 votes |
@Test public void testRebuildSelector() throws Exception { EventLoopGroup group = new NioEventLoopGroup(1); final NioEventLoop loop = (NioEventLoop) group.next(); try { Channel channel = new NioServerSocketChannel(); loop.register(channel).syncUninterruptibly(); Selector selector = loop.unwrappedSelector(); assertSame(selector, ((NioEventLoop) channel.eventLoop()).unwrappedSelector()); assertTrue(selector.isOpen()); // Submit to the EventLoop so we are sure its really executed in a non-async manner. loop.submit(new Runnable() { @Override public void run() { loop.rebuildSelector(); } }).syncUninterruptibly(); Selector newSelector = ((NioEventLoop) channel.eventLoop()).unwrappedSelector(); assertTrue(newSelector.isOpen()); assertNotSame(selector, newSelector); assertFalse(selector.isOpen()); channel.close().syncUninterruptibly(); } finally { group.shutdownGracefully(); } }
Example #14
Source File: AcceptorImpl.java From gemfirexd-oss with Apache License 2.0 | 5 votes |
/** wake up the selector thread */ private void wakeupSelector() { Selector s = getSelector(); if (s != null && s.isOpen()) { this.selector.wakeup(); } }
Example #15
Source File: TNonblockingServerSocket.java From incubator-retired-blur with Apache License 2.0 | 5 votes |
public void registerSelector(Selector selector) { try { // Register the server socket channel, indicating an interest in // accepting new connections serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); } catch (ClosedChannelException e) { // this shouldn't happen, ideally... // TODO: decide what to do with this. } }
Example #16
Source File: MoldUDP64.java From nassau with Apache License 2.0 | 5 votes |
/** * Receive messages. Invoke the message listener on each message. Continue * until a packet indicating the End of Session is received. * * @param multicastInterface the multicast interface * @param multicastGroup the multicast group * @param requestAddress the request address * @param listener a message listener * @throws IOException if an I/O error occurs */ public static void receive(NetworkInterface multicastInterface, InetSocketAddress multicastGroup, InetSocketAddress requestAddress, MessageListener listener) throws IOException { DatagramChannel channel = DatagramChannel.open(StandardProtocolFamily.INET); channel.setOption(StandardSocketOptions.SO_REUSEADDR, true); channel.bind(new InetSocketAddress(multicastGroup.getPort())); channel.join(multicastGroup.getAddress(), multicastInterface); channel.configureBlocking(false); DatagramChannel requestChannel = DatagramChannel.open(StandardProtocolFamily.INET); requestChannel.configureBlocking(false); StatusListener statusListener = new StatusListener(); try (Selector selector = Selector.open(); MoldUDP64Client client = new MoldUDP64Client(channel, requestChannel, requestAddress, listener, statusListener)) { SelectionKey channelKey = channel.register(selector, SelectionKey.OP_READ); SelectionKey requestChannelKey = requestChannel.register(selector, SelectionKey.OP_READ); while (statusListener.receive) { while (selector.select() == 0); Set<SelectionKey> selectedKeys = selector.selectedKeys(); if (selectedKeys.contains(channelKey)) client.receive(); if (selectedKeys.contains(requestChannelKey)) client.receiveResponse(); selectedKeys.clear(); } } }
Example #17
Source File: Utils.java From datakernel with Apache License 2.0 | 5 votes |
/** * Replaces the selected keys field from {@link java.util.HashSet} in {@link sun.nio.ch.SelectorImpl} * to {@link OptimizedSelectedKeysSet} to avoid overhead which causes a work of GC * * @param selector selector instance whose selected keys field is to be changed * @return <code>true</code> on success */ public static boolean tryToOptimizeSelector(Selector selector) { OptimizedSelectedKeysSet selectedKeys = new OptimizedSelectedKeysSet(); try { SELECTED_KEYS_FIELD.set(selector, selectedKeys); PUBLIC_SELECTED_KEYS_FIELD.set(selector, selectedKeys); return true; } catch (IllegalAccessException e) { logger.warn("Failed setting optimized set into selector", e); } return false; }
Example #18
Source File: TcpSquirtOutboundTransport.java From defense-solutions-proofs-of-concept with Apache License 2.0 | 5 votes |
private void applyProperties() throws IOException { if(mode==SERVER) { selector = Selector.open(); } }
Example #19
Source File: Server.java From hadoop with Apache License 2.0 | 5 votes |
Reader(String name) throws IOException { super(name); this.pendingConnections = new LinkedBlockingQueue<Connection>(readerPendingConnectionQueue); this.readSelector = Selector.open(); }
Example #20
Source File: NIOConnector.java From ServletContainer with GNU General Public License v3.0 | 5 votes |
public NIOConnector init() { try { this.selector = Selector.open(); ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.configureBlocking(false); ServerSocket serverSocket = serverSocketChannel.socket(); InetSocketAddress inetSocketAddress = new InetSocketAddress(80); serverSocket.bind(inetSocketAddress); serverSocketChannel.register(this.selector, SelectionKey.OP_ACCEPT); }catch(IOException e){ e.printStackTrace(); } return this; }
Example #21
Source File: DatagramChannelDispatcher.java From localization_nifi with Apache License 2.0 | 5 votes |
@Override public void open(final InetAddress nicAddress, final int port, final int maxBufferSize) throws IOException { stopped = false; datagramChannel = DatagramChannel.open(); datagramChannel.configureBlocking(false); if (maxBufferSize > 0) { datagramChannel.setOption(StandardSocketOptions.SO_RCVBUF, maxBufferSize); final int actualReceiveBufSize = datagramChannel.getOption(StandardSocketOptions.SO_RCVBUF); if (actualReceiveBufSize < maxBufferSize) { logger.warn("Attempted to set Socket Buffer Size to " + maxBufferSize + " bytes but could only set to " + actualReceiveBufSize + "bytes. You may want to consider changing the Operating System's " + "maximum receive buffer"); } } // we don't have to worry about nicAddress being null here because InetSocketAddress already handles it datagramChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true); datagramChannel.socket().bind(new InetSocketAddress(nicAddress, port)); // if a sending host and port were provided then connect to that specific address to only receive // datagrams from that host/port, otherwise we can receive datagrams from any host/port if (sendingHost != null && sendingPort != null) { datagramChannel.connect(new InetSocketAddress(sendingHost, sendingPort)); } selector = Selector.open(); datagramChannel.register(selector, SelectionKey.OP_READ); }
Example #22
Source File: NioTcpClient.java From dnsjava with BSD 2-Clause "Simplified" License | 5 votes |
private static void processPendingRegistrations() { while (!registrationQueue.isEmpty()) { ChannelState state = registrationQueue.remove(); try { final Selector selector = selector(); if (!state.channel.isConnected()) { state.channel.register(selector, SelectionKey.OP_CONNECT, state); } else { state.channel.keyFor(selector).interestOps(SelectionKey.OP_WRITE); } } catch (IOException e) { state.handleChannelException(e); } } }
Example #23
Source File: ChannelListener.java From localization_nifi with Apache License 2.0 | 5 votes |
public ChannelListener(final int threadPoolSize, final StreamConsumerFactory consumerFactory, final BufferPool bufferPool, int timeout, TimeUnit unit, final boolean readSingleDatagram) throws IOException { this.executor = Executors.newScheduledThreadPool(threadPoolSize + 1); // need to allow for long running ChannelDispatcher thread this.serverSocketSelector = Selector.open(); this.socketChannelSelector = Selector.open(); this.bufferPool = bufferPool; this.initialBufferPoolSize = bufferPool.size(); channelDispatcher = new ChannelDispatcher(serverSocketSelector, socketChannelSelector, executor, consumerFactory, bufferPool, timeout, unit, readSingleDatagram); executor.schedule(channelDispatcher, 50, TimeUnit.MILLISECONDS); }
Example #24
Source File: IOUtils.java From JobX with Apache License 2.0 | 5 votes |
public static void closeQuietly(Selector selector) { if (selector != null) { try { selector.close(); } catch (IOException var2) { ; } } }
Example #25
Source File: Server.java From stratosphere with Apache License 2.0 | 5 votes |
Responder() throws IOException { this.setName("IPC Server Responder"); this.setDaemon(true); writeSelector = Selector.open(); // create a selector pending = 0; }
Example #26
Source File: Sender.java From cacheonix-core with GNU Lesser General Public License v2.1 | 5 votes |
/** * Creates message sender. * * @param localAddress the localAddress. * @param networkTimeoutMillis a network timeout in milliseconds. * @param selectorTimeoutMillis a time the selector should block for while waiting for a channel to become ready, * must be greater than zero. * @param clock the clock. */ public Sender(final ClusterNodeAddress localAddress, final long networkTimeoutMillis, final long selectorTimeoutMillis, final Clock clock) throws IOException { super("Sender:" + localAddress.getTcpPort()); this.selectorTimeoutMillis = selectorTimeoutMillis; this.networkTimeoutMillis = networkTimeoutMillis; this.localAddress = localAddress; this.selector = Selector.open(); this.clock = clock; }
Example #27
Source File: NIOAcceptor.java From Mycat2 with GNU General Public License v3.0 | 5 votes |
/** * 仅后台维护的主动创建的连接使用 */ private void openServerChannel(Selector selector, String bindIp, int bindPort) throws IOException { serverChannel = ServerSocketChannel.open(); final InetSocketAddress isa = new InetSocketAddress(bindIp, bindPort); serverChannel.bind(isa); serverChannel.configureBlocking(false); serverChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true); serverChannel.register(selector, SelectionKey.OP_ACCEPT); }
Example #28
Source File: SelectorManager.java From IoTgo_Android_App with MIT License | 5 votes |
public void dumpKeyState(List<Object> dumpto) { Selector selector=_selector; Set<SelectionKey> keys = selector.keys(); dumpto.add(selector + " keys=" + keys.size()); for (SelectionKey key: keys) { if (key.isValid()) dumpto.add(key.attachment()+" iOps="+key.interestOps()+" rOps="+key.readyOps()); else dumpto.add(key.attachment()+" iOps=-1 rOps=-1"); } }
Example #29
Source File: NioEventLoop.java From getty with Apache License 2.0 | 5 votes |
public NioEventLoop(BaseConfig config, ChunkPool chunkPool) { this.config = config; this.chunkPool = chunkPool; this.workerThreadPool = new ThreadPool(ThreadPool.FixedThread, 2); //初始化数据输出类 nioBufferWriter = new NioBufferWriter(chunkPool, config.getBufferWriterQueueSize(), config.getChunkPoolBlockTime()); try { selector = new SelectedSelector(Selector.open()); } catch (IOException e) { e.printStackTrace(); } }
Example #30
Source File: NetworkSelector.java From tribaltrouble with GNU General Public License v2.0 | 5 votes |
final Selector getSelector() { try { initSelector(); } catch (IOException e) { throw new RuntimeException(e); } return selector; }