Example usage for java.nio.channels SelectionKey isWritable

List of usage examples for java.nio.channels SelectionKey isWritable

Introduction

In this page you can find the example usage for java.nio.channels SelectionKey isWritable.

Prototype

public final boolean isWritable() 

Source Link

Document

Tests whether this key's channel is ready for writing.

Usage

From source file:org.quickserver.net.server.QuickServer.java

/**
 * Starts server in non-blocking mode./* w  ww .j av  a2 s .  c o  m*/
 * @since 1.4.5
 */
private void runNonBlocking(TheClient theClient) throws Exception {
    int selectCount = 0;
    Iterator iterator = null;
    SelectionKey key = null;
    ServerSocketChannel serverChannel = null;
    SocketChannel socketChannel = null;
    Socket client = null;
    ClientHandler _chPolled = null;
    boolean stopServerProcessed = false;
    int linger = getBasicConfig().getAdvancedSettings().getSocketLinger();
    registerChannelRequestMap = new HashMap();

    int socketTrafficClass = 0;
    if (getBasicConfig().getAdvancedSettings().getClientSocketTrafficClass() != null) {
        socketTrafficClass = Integer
                .parseInt(getBasicConfig().getAdvancedSettings().getClientSocketTrafficClass());
    }

    while (true) {
        selectCount = selector.select(500);
        //selectCount = selector.select();//for testing

        //check for any pending registerChannel req.
        synchronized (registerChannelRequestMap) {
            if (registerChannelRequestMap.size() > 0) {
                RegisterChannelRequest req = null;
                Object hashkey = null;
                iterator = registerChannelRequestMap.keySet().iterator();
                while (iterator.hasNext()) {
                    hashkey = iterator.next();
                    req = (RegisterChannelRequest) registerChannelRequestMap.get(hashkey);
                    req.register(getSelector());
                }
                iterator = null;
                registerChannelRequestMap.clear();
            } //if
        } //sync

        if (stopServer == true && stopServerProcessed == false) {
            logger.warning("Closing " + getName());
            serverSocketChannel.close();
            stopServerProcessed = true;

            server = null;
            serverSocketChannel = null;

            setServiceState(Service.STOPPED);
            logger.warning("Closed " + getName());

            processServerHooks(ServerHook.POST_SHUTDOWN);
        }

        if (stopServer == false && stopServerProcessed == true) {
            logger.finest("Server must have re-started.. will break");
            break;
        }

        if (selectCount == 0 && stopServerProcessed == true) {
            java.util.Set keyset = selector.keys();
            if (keyset.isEmpty() == true && getClientCount() <= 0) {
                break;
            } else {
                continue;
            }
        } else if (selectCount == 0) {
            continue;
        }

        iterator = selector.selectedKeys().iterator();
        while (iterator.hasNext()) {
            key = (SelectionKey) iterator.next();

            if (key.isValid() == false) {
                iterator.remove();
                continue;
            }

            if (key.isAcceptable() && stopServer == false) {
                logger.finest("Key is Acceptable");
                serverChannel = (ServerSocketChannel) key.channel();
                socketChannel = serverChannel.accept();

                if (socketChannel == null) {
                    iterator.remove();
                    continue;
                }

                client = socketChannel.socket();

                if (linger < 0) {
                    client.setSoLinger(false, 0);
                } else {
                    client.setSoLinger(true, linger);
                }

                client.setTcpNoDelay(getBasicConfig().getAdvancedSettings().getClientSocketTcpNoDelay());

                if (getBasicConfig().getAdvancedSettings().getClientSocketTrafficClass() != null) {
                    client.setTrafficClass(socketTrafficClass);//low delay=10
                }

                //logger.fine("ReceiveBufferSize: "+client.getReceiveBufferSize());

                if (getBasicConfig().getAdvancedSettings().getClientSocketSendBufferSize() != 0) {
                    client.setSendBufferSize(
                            getBasicConfig().getAdvancedSettings().getClientSocketSendBufferSize());
                    //logger.fine("SendBufferSize: "+client.getSendBufferSize());
                }

                if (checkAccessConstraint(client) == false) {
                    iterator.remove();
                    continue;
                }

                socketChannel.configureBlocking(false);
                theClient.setTrusted(getSkipValidation());
                theClient.setSocket(socketChannel.socket());
                theClient.setSocketChannel(socketChannel);

                if (clientDataClass != null) {
                    if (getClientDataPool() == null) {
                        clientData = (ClientData) clientDataClass.newInstance();
                    } else {
                        //borrow a object from pool
                        clientData = (ClientData) getClientDataPool().borrowObject();
                    }
                    theClient.setClientData(clientData);
                }

                //Check if max connection has reached
                if (getSkipValidation() != true && maxConnection != -1
                        && getClientHandlerPool().getNumActive() >= maxConnection) {
                    theClient.setClientEvent(ClientEvent.MAX_CON);
                } else {
                    theClient.setClientEvent(ClientEvent.ACCEPT);
                }

                try {
                    _chPolled = (ClientHandler) getClientHandlerPool().borrowObject();
                    logger.finest("Asking " + _chPolled.getName() + " to handle.");
                    _chPolled.handleClient(theClient);
                } catch (java.util.NoSuchElementException nsee) {
                    logger.warning("Could not borrow ClientHandler Object from pool. Error: " + nsee);
                    logger.warning("Closing SocketChannel [" + serverChannel.socket()
                            + "] since no ClientHandler available.");
                    socketChannel.close();
                }

                if (_chPolled != null) {
                    try {
                        getClientPool().addClient(_chPolled, true);
                    } catch (java.util.NoSuchElementException nsee) {
                        logger.warning("Could not borrow Thread from pool. Error: " + nsee);
                        //logger.warning("Closing SocketChannel ["+serverChannel.socket()+"] since no Thread available.");
                        //socketChannel.close();
                        //returnClientHandlerToPool(_chPolled);
                    }
                    _chPolled = null;
                }
                socketChannel = null;
                client = null;

                setSkipValidation(false);//reset it back
            } else if (key.isValid() && key.isReadable()) {
                boolean addedEvent = false;
                ClientHandler _ch = null;
                try {
                    _ch = (ClientHandler) key.attachment();
                    logger.finest("Key is Readable, removing OP_READ from interestOps for " + _ch.getName());
                    key.interestOps(key.interestOps() & (~SelectionKey.OP_READ));
                    _ch.addEvent(ClientEvent.READ);
                    addedEvent = true;
                    //_ch.setSelectionKey(key);
                    getClientPool().addClient(_ch);
                } catch (CancelledKeyException cke) {
                    logger.fine("Ignored Error - Key was Cancelled: " + cke);
                } catch (java.util.NoSuchElementException nsee) {
                    logger.finest("NoSuchElementException: " + nsee);
                    if (addedEvent)
                        _ch.removeEvent(ClientEvent.READ);
                    continue;//no need to remove the key
                }
                _ch = null;
            } else if (key.isValid() && key.isWritable()) {
                if (getClientPool().shouldNioWriteHappen() == false) {
                    continue; //no need to remove the key
                }
                boolean addedEvent = false;
                ClientHandler _ch = null;
                try {
                    _ch = (ClientHandler) key.attachment();
                    logger.finest("Key is Writable, removing OP_WRITE from interestOps for " + _ch.getName());
                    //remove OP_WRITE from interest set
                    key.interestOps(key.interestOps() & (~SelectionKey.OP_WRITE));
                    _ch.addEvent(ClientEvent.WRITE);
                    addedEvent = true;
                    //_ch.setSelectionKey(key);
                    getClientPool().addClient(_ch);
                } catch (CancelledKeyException cke) {
                    logger.fine("Ignored Error - Key was Cancelled: " + cke);
                } catch (java.util.NoSuchElementException nsee) {
                    logger.finest("NoSuchElementException: " + nsee);
                    if (addedEvent)
                        _ch.removeEvent(ClientEvent.WRITE);
                    continue;//no need to remove the key
                }
                _ch = null;
            } else if (stopServer == true && key.isAcceptable()) {
                //we will not accept this key
                setSkipValidation(false);//reset it back
            } else {
                logger.warning("Unknown key got in SelectionKey: " + key);
            }
            iterator.remove(); //Remove key

            Thread.yield();
        } //end of iterator
        iterator = null;
    } //end of loop
}

From source file:voldemort.common.nio.AbstractSelectorManager.java

public void run() {
    threadName = Thread.currentThread().getName();

    try {//from   w  ww  .  j av  a  2 s .c  om
        while (true) {
            if (isClosed.get()) {
                logger.debug("SelectorManager is closed, exiting");

                break;
            }

            lastHeartBeatTimeMs = System.currentTimeMillis();
            processEvents();

            try {
                selectTimeMs = System.currentTimeMillis();
                int selected = selector.select(SELECTOR_POLL_MS);
                selectTimeMs = System.currentTimeMillis() - selectTimeMs;
                selectCount = selected;

                if (isClosed.get()) {
                    logger.debug("SelectorManager is closed, exiting");

                    break;
                }

                if (selected > 0) {
                    processingTimeMs = System.currentTimeMillis();
                    Iterator<SelectionKey> i = selector.selectedKeys().iterator();

                    while (i.hasNext()) {
                        SelectionKey selectionKey = i.next();
                        i.remove();

                        if (selectionKey.isValid() && (selectionKey.isConnectable() || selectionKey.isReadable()
                                || selectionKey.isWritable())) {
                            Runnable worker = (Runnable) selectionKey.attachment();
                            worker.run();
                        }
                    }
                    processingTimeMs = System.currentTimeMillis() - processingTimeMs;
                }
            } catch (ClosedSelectorException e) {
                logger.debug("SelectorManager is closed, exiting");

                break;
            } catch (Throwable t) {
                if (logger.isEnabledFor(Level.ERROR))
                    logger.error(t.getMessage(), t);
            }
        }
    } catch (Throwable t) {
        if (logger.isEnabledFor(Level.ERROR))
            logger.error(t.getMessage(), t);
    } finally {
        try {
            close();
        } catch (Exception e) {
            if (logger.isEnabledFor(Level.ERROR))
                logger.error(e.getMessage(), e);
        }
    }
}

From source file:voldemort.common.nio.SelectorManagerWorker.java

public void run() {
    try {//  w  w w .  j  a v a 2  s  .co m
        SelectionKey selectionKey = socketChannel.keyFor(selector);

        if (selectionKey.isConnectable())
            connect(selectionKey);
        else if (selectionKey.isReadable())
            read(selectionKey);
        else if (selectionKey.isWritable())
            write(selectionKey);
        else if (!selectionKey.isValid())
            throw new IllegalStateException("Selection key not valid for " + socketChannel.socket());
        else
            throw new IllegalStateException(
                    "Unknown state, not readable, writable, or valid for " + socketChannel.socket());
    } catch (ClosedByInterruptException e) {
        reportException(e);
        close();
    } catch (CancelledKeyException e) {
        close();
    } catch (EOFException e) {
        // EOFException is expected, hence no logging, otherwise this block
        // could be combined with IOException
        reportException(e);
        close();
    } catch (IOException e) {
        logger.info("Connection reset from " + socketChannel.socket() + " with message - " + e.getMessage());
        reportException(e);
        close();
    } catch (Throwable t) {
        logger.error("Caught throwable from " + socketChannel.socket(), t);
        close();
    }
}