Package java.nio.channels

Examples of java.nio.channels.Selector


    }

    void flush( SocketSessionImpl session )
    {
        scheduleFlush( session );
        Selector selector = this.selector;
        if( selector != null )
        {
            selector.wakeup();
        }
    }


        if( localAddress == null )
        {
            throw new NullPointerException( "localAddress" );
        }
       
        Selector selector = this.selector;
        DatagramChannel ch = ( DatagramChannel ) channels.get( localAddress );
        if( selector == null || ch == null )
        {
            throw new IllegalArgumentException( "Unknown localAddress: " + localAddress );
        }

    }

    public void flushSession( DatagramSessionImpl session )
    {
        scheduleFlush( session );
        Selector selector = this.selector;
        if( selector != null )
        {
            selector.wakeup();
        }
    }

            SelectionKey key=null;
           
            try
            {
                List changes;
                final Selector selector;
                synchronized (_changes)
                {
                    changes=_changes[_change];
                    _change=_change==0?1:0;
                    _selecting=true;
                    selector=_selector;
                }

                // Make any key changes required
                try
                {
                  for (int i = 0; i < changes.size(); i++)
                  {
                    try
                    {
                      Object o = changes.get(i);

                      if (o instanceof EndPoint)
                      {
                        // Update the operations for a key.
                        SelectChannelEndPoint endpoint = (SelectChannelEndPoint)o;
                        endpoint.doUpdateKey();
                      }
                      else if (o instanceof Runnable)
                      {
                        dispatch((Runnable)o);
                      }
                      else if (o instanceof ChangeSelectableChannel)
                      {
                        // finish accepting/connecting this connection
                        final ChangeSelectableChannel asc = (ChangeSelectableChannel)o;
                        final SelectableChannel channel=asc._channel;
                        final Object att = asc._attachment;

                        if ((channel instanceof SocketChannel) && ((SocketChannel)channel).isConnected())
                        {
                          key = channel.register(selector,SelectionKey.OP_READ,att);
                          SelectChannelEndPoint endpoint = newEndPoint((SocketChannel)channel,this,key);
                          key.attach(endpoint);
                          endpoint.dispatch();
                        }
                        else if (channel.isOpen())
                        {
                          channel.register(selector,SelectionKey.OP_CONNECT,att);
                        }
                      }
                      else if (o instanceof SocketChannel)
                      {
                        final SocketChannel channel=(SocketChannel)o;

                        if (channel.isConnected())
                        {
                          key = channel.register(selector,SelectionKey.OP_READ,null);
                          SelectChannelEndPoint endpoint = newEndPoint(channel,this,key);
                          key.attach(endpoint);
                          endpoint.dispatch();
                        }
                        else if (channel.isOpen())
                        {
                          channel.register(selector,SelectionKey.OP_CONNECT,null);
                        }
                      }
                      else if (o instanceof ServerSocketChannel)
                      {
                        ServerSocketChannel channel = (ServerSocketChannel)o;
                        channel.register(getSelector(),SelectionKey.OP_ACCEPT);
                      }
                      else if (o instanceof ChangeTask)
                      {
                        ((ChangeTask)o).run();
                      }
                      else
                        throw new IllegalArgumentException(o.toString());
                    }
                    catch (Exception e)
                    {
                      if (isRunning())
                        Log.warn(e);
                      else
                        Log.debug(e);
                    }
                    catch (Error e)
                    {
                      if (isRunning())
                        Log.warn(e);
                      else
                        Log.debug(e);
                    }
                  }
                }
                finally
                {
                  changes.clear();
                }
               
                long idle_next = 0;
                long retry_next = 0;
                long now=System.currentTimeMillis();
                synchronized (this)
                {
                    _idleTimeout.setNow(now);
                    _retryTimeout.setNow(now);
                    if (_lowResourcesConnections>0 && selector.keys().size()>_lowResourcesConnections)
                        _idleTimeout.setDuration(_lowResourcesMaxIdleTime);
                    else
                        _idleTimeout.setDuration(_maxIdleTime);
                    idle_next=_idleTimeout.getTimeToNext();
                    retry_next=_retryTimeout.getTimeToNext();
                }

                // workout how low to wait in select
                long wait = 1000L// not getMaxIdleTime() as the now value of the idle timers needs to be updated.
                if (idle_next >= 0 && wait > idle_next)
                    wait = idle_next;
                if (wait > 0 && retry_next >= 0 && wait > retry_next)
                    wait = retry_next;
   
                // Do the select.
                if (wait > 2) // TODO tune or configure this
                {
                    // If we are in pausing mode
                    if (_pausing)
                    {
                        try
                        {
                            Thread.sleep(__BUSY_PAUSE); // pause to reduce impact of  busy loop
                        }
                        catch(InterruptedException e)
                        {
                            Log.ignore(e);
                        }
                    }
                       
                    long before=now;
                    int selected=selector.select(wait);
                    now = System.currentTimeMillis();
                    _idleTimeout.setNow(now);
                    _retryTimeout.setNow(now);
                    _selects++;

                    // Look for JVM bugs over a monitor period.
                    // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6403933
                    // http://bugs.sun.com/view_bug.do?bug_id=6693490
                    if (now>_monitorNext)
                    {
                        _selects=(int)(_selects*__MONITOR_PERIOD/(now-_monitorStart));
                        _pausing=_selects>__MAX_SELECTS;
                        if (_pausing)
                            _paused++;
                           
                        _selects=0;
                        _jvmBug=0;
                        _monitorStart=now;
                        _monitorNext=now+__MONITOR_PERIOD;
                    }
                   
                    if (now>_log)
                    {
                        if (_paused>0
                            Log.info(this+" Busy selector - injecting delay "+_paused+" times");

                        if (_jvmFix2>0)
                            Log.info(this+" JVM BUG(s) - injecting delay"+_jvmFix2+" times");

                        if (_jvmFix1>0)
                            Log.info(this+" JVM BUG(s) - recreating selector "+_jvmFix1+" times, canceled keys "+_jvmFix0+" times");

                        else if(Log.isDebugEnabled() && _jvmFix0>0)
                            Log.info(this+" JVM BUG(s) - canceled keys "+_jvmFix0+" times");
                        _paused=0;
                        _jvmFix2=0;
                        _jvmFix1=0;
                        _jvmFix0=0;
                        _log=now+60000;
                    }
                   
                    // If we see signature of possible JVM bug, increment count.
                    if (selected==0 && wait>10 && (now-before)<(wait/2))
                    {
                        // Increment bug count and try a work around
                        _jvmBug++;
                        if (_jvmBug>(__JVMBUG_THRESHHOLD))
                        {
                            try
                            {
                                if (_jvmBug==__JVMBUG_THRESHHOLD+1)
                                    _jvmFix2++;
                                   
                                Thread.sleep(__BUSY_PAUSE); // pause to avoid busy loop
                            }
                            catch(InterruptedException e)
                            {
                                Log.ignore(e);
                            }
                        }
                        else if (_jvmBug==__JVMBUG_THRESHHOLD)
                        {
                            synchronized (this)
                            {
                                // BLOODY SUN BUG !!!  Try refreshing the entire selector.
                                _jvmFix1++;
                               
                                final Selector new_selector = Selector.open();
                                Iterator iterator = _selector.keys().iterator();
                                while (iterator.hasNext())
                                {
                                    SelectionKey k = (SelectionKey)iterator.next();
                                    if (!k.isValid() || k.interestOps()==0)
                                        continue;
                                   
                                    final SelectableChannel channel = k.channel();
                                    final Object attachment = k.attachment();
                                   
                                    if (attachment==null)
                                        addChange(channel);
                                    else
                                        addChange(channel,attachment);
                                }
                                Selector old_selector=_selector;
                                _selector=new_selector;
                                try
                                {
                                    old_selector.close();
                                }
                                catch(Exception e)
                                {
                                    Log.warn(e);
                                }

        }

        /* ------------------------------------------------------------ */
        public void wakeup()
        {
            Selector selector = _selector;
            if (selector!=null)
                selector.wakeup();
        }

                             + socketChannel.socket().getSendBufferSize() + " bytes.");

            ClientRequestSelectorManager selectorManager = selectorManagers[counter.getAndIncrement()
                                                                            % selectorManagers.length];

            Selector selector = selectorManager.getSelector();
            clientRequestExecutor = new ClientRequestExecutor(selector,
                                                              socketChannel,
                                                              socketBufferSize);
            int timeoutMs = this.getTimeout();
            BlockingClientRequest<String> clientRequest = new BlockingClientRequest<String>(new ProtocolNegotiatorClientRequest(dest.getRequestFormatType()),
                                                                                            timeoutMs);
            clientRequestExecutor.addClientRequest(clientRequest, timeoutMs, 0);

            selectorManager.registrationQueue.add(clientRequestExecutor);
            selector.wakeup();

            // Block while we wait for protocol negotiation to complete. May
            // throw interrupted exception
            boolean awaitResult = clientRequest.await();

            super();
        }

        void register(NioSocketChannel channel) {
            boolean firstChannel = started.compareAndSet(false, true);
            Selector selector;
            if (firstChannel) {
                try {
                    this.selector = selector = Selector.open();
                } catch (IOException e) {
                    throw new ChannelException(
                            "Failed to create a selector.", e);
                }
            } else {
                selector = this.selector;
                if (selector == null) {
                    do {
                        Thread.yield();
                        selector = this.selector;
                    } while (selector == null);
                }
            }

            if (firstChannel) {
                try {
                    channel.socket.register(selector, SelectionKey.OP_CONNECT, channel);
                } catch (ClosedChannelException e) {
                    throw new ChannelException(
                            "Failed to register a socket to the selector.", e);
                }
                bossExecutor.execute(new ThreadRenamingRunnable(
                        this, "New I/O client boss #" + id));
            } else {
                synchronized (selectorGuard) {
                    selector.wakeup();
                    try {
                        channel.socket.register(selector, SelectionKey.OP_CONNECT, channel);
                    } catch (ClosedChannelException e) {
                        throw new ChannelException(
                                "Failed to register a socket to the selector.", e);

            }
        }

        public void run() {
            boolean shutdown = false;
            Selector selector = this.selector;
            for (;;) {
                synchronized (selectorGuard) {
                    // This empty synchronization block prevents the selector
                    // from acquiring its lock.
                }
                try {
                    int selectedKeyCount = selector.select(500);
                    if (selectedKeyCount > 0) {
                        processSelectedKeys(selector.selectedKeys());
                    }

                    // Exit the loop when there's nothing to handle.
                    // The shutdown flag is used to delay the shutdown of this
                    // loop to avoid excessive Selector creation when
                    // connection attempts are made in a one-by-one manner
                    // instead of concurrent manner.
                    if (selector.keys().isEmpty()) {
                        if (shutdown ||
                            bossExecutor instanceof ExecutorService && ((ExecutorService) bossExecutor).isShutdown()) {

                            synchronized (selectorGuard) {
                                if (selector.keys().isEmpty()) {
                                    try {
                                        selector.close();
                                    } catch (IOException e) {
                                        logger.warn(
                                                "Failed to close a selector.",
                                                e);
                                    } finally {

    void register(NioSocketChannel channel, ChannelFuture future) {

        boolean server = !(channel instanceof NioClientSocketChannel);
        Runnable registerTask = new RegisterTask(channel, future, server);
        Selector selector;

        synchronized (startStopLock) {
            if (!started) {
                // Open a selector if this worker didn't start yet.
                try {
                    this.selector = selector = Selector.open();
                } catch (Throwable t) {
                    throw new ChannelException(
                            "Failed to create a selector.", t);
                }

                // Start the worker thread with the new Selector.
                String threadName =
                    (server ? "New I/O server worker #"
                            : "New I/O client worker #") + bossId + '-' + id;

                boolean success = false;
                try {
                    executor.execute(new ThreadRenamingRunnable(this, threadName));
                    success = true;
                } finally {
                    if (!success) {
                        // Release the Selector if the execution fails.
                        try {
                            selector.close();
                        } catch (Throwable t) {
                            logger.warn("Failed to close a selector.", t);
                        }
                        this.selector = selector = null;
                        // The method will return to the caller at this point.
                    }
                }
            } else {
                // Use the existing selector if this worker has been started.
                selector = this.selector;
            }

            assert selector != null && selector.isOpen();

            started = true;
            registerTaskQueue.offer(registerTask);
        }

        if (wakenUp.compareAndSet(false, true)) {
            selector.wakeup();
        }
    }

    public void run() {
        thread = Thread.currentThread();

        boolean shutdown = false;
        Selector selector = this.selector;
        for (;;) {
            wakenUp.set(false);

            if (CONSTRAINT_LEVEL != 0) {
                selectorGuard.writeLock().lock();
                    // This empty synchronization block prevents the selector
                    // from acquiring its lock.
                selectorGuard.writeLock().unlock();
            }

            try {
                int selectedKeyCount = selector.select(500);

                processRegisterTaskQueue();
                processWriteTaskQueue();

                if (selectedKeyCount > 0) {
                    processSelectedKeys(selector.selectedKeys());
                }

                // Exit the loop when there's nothing to handle.
                // The shutdown flag is used to delay the shutdown of this
                // loop to avoid excessive Selector creation when
                // connections are registered in a one-by-one manner instead of
                // concurrent manner.
                if (selector.keys().isEmpty()) {
                    if (shutdown ||
                        executor instanceof ExecutorService && ((ExecutorService) executor).isShutdown()) {

                        synchronized (startStopLock) {
                            if (registerTaskQueue.isEmpty() && selector.keys().isEmpty()) {
                                started = false;
                                try {
                                    selector.close();
                                } catch (IOException e) {
                                    logger.warn(
                                            "Failed to close a selector.", e);
                                } finally {
                                    this.selector = null;

TOP

Related Classes of java.nio.channels.Selector

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.