com.sun.grizzly
Class TCPSelectorHandler

java.lang.Object
  extended by com.sun.grizzly.TCPSelectorHandler
All Implemented Interfaces:
Handler, SelectorHandler, AttributeHolder, Copyable, SupportStateHolder<State>
Direct Known Subclasses:
RoundRobinSelectorHandler, SelectorThreadHandler, SSLSelectorHandler, UDPSelectorHandler

public class TCPSelectorHandler
extends Object
implements SelectorHandler

A SelectorHandler handles all java.nio.channels.Selector operations. One or more instance of a Selector are handled by SelectorHandler. The logic for processing of SelectionKey interest (OP_ACCEPT,OP_READ, etc.) is usually defined using an instance of SelectorHandler. This class represents a TCP implementation of a SelectorHandler. This class first bind a ServerSocketChannel to a TCP port and then start waiting for NIO events.

Author:
Jeanfrancois Arcand

Field Summary
protected  AsyncQueueReader asyncQueueReader
          AsyncQueueWriter
protected  AsyncQueueWriter asyncQueueWriter
          AsyncQueueWriter
protected  Map<String,Object> attributes
          Attributes, associated with the SelectorHandler instance
protected  ConnectorInstanceHandler connectorInstanceHandler
          The ConnectorInstanceHandler used to return a new or pooled ConnectorHandler
protected  InetAddress inet
          The inet address to use when binding.
protected  ProtocolChainInstanceHandler instanceHandler
          The ProtocolChainInstanceHandler used by this instance.
protected  boolean isClient
          Is this used for client only or client/server operation.
protected  AtomicBoolean isShutDown
          Flag, which shows whether shutdown was called for this SelectorHandler
protected  int linger
          The socket linger.
protected  Logger logger
           
protected  ConcurrentLinkedQueue<SelectionKeyOP> opToRegister
          The list of SelectionKeyOP to register next time the Selector.select is invoked.
protected  Pipeline pipeline
          The Pipeline used by this instance.
protected  int port
          The default TCP port.
protected  boolean reuseAddress
          The socket reuseAddress
protected  SelectionKeyHandler selectionKeyHandler
          The SelectionKeyHandler associated with this SelectorHandler.
protected  Selector selector
          The single Selector.
protected  long selectTimeout
          The Selector time out.
protected  ServerSocket serverSocket
          The ServerSocket instance.
protected  ServerSocketChannel serverSocketChannel
          The ServerSocketChannel.
protected  int serverTimeout
          The server socket time out
protected  int socketTimeout
          The socket time out
protected  int ssBackLog
          Server socket backlog.
protected  StateHolder<State> stateHolder
          This SelectorHandler StateHolder, which is shared among SelectorHandler and its clones
protected  boolean tcpNoDelay
          The socket tcpDelay.
 
Constructor Summary
TCPSelectorHandler()
           
TCPSelectorHandler(boolean isClient)
          Create a TCPSelectorHandler only used with ConnectorHandler.
 
Method Summary
 SelectableChannel acceptWithoutRegistration(SelectionKey key)
          Accepts connection, without registering it for reading or writing
 ConnectorHandler acquireConnectorHandler()
          Return an instance of the default ConnectorHandler, which is the TCPConnectorHandler
 void closeChannel(SelectableChannel channel)
          Closes SelectableChannel
 void configureChannel(SelectableChannel channel)
          Configure the channel operations.
protected  void connect(SocketAddress remoteAddress, SocketAddress localAddress, CallbackHandler callBackHandler)
          Register a CallBackHandler to this Selector.
 void copyTo(Copyable copy)
          Copies current object content to copy object
 AsyncQueueReader getAsyncQueueReader()
          Returns AsyncQueueReader associated with this SelectorHandler.
 AsyncQueueWriter getAsyncQueueWriter()
          Returns AsyncQueueWriter associated with this SelectorHandler.
 Object getAttribute(String key)
          Return an object based on a key.
 Map<String,Object> getAttributes()
          Return a Map of attribute name/value pairs.
protected  Callable<ConnectorHandler> getConnectorInstanceHandlerDelegate()
          Return factory object, which knows how to create ConnectorInstanceHandler corresponding to the protocol
 InetAddress getInet()
           
 int getLinger()
           
 Logger getLogger()
           
 int getPort()
           
 int getPortLowLevel()
          Returns port number SelectorHandler is listening on Similar to getPort(), but getting port number directly from connection (ServerSocket, DatagramSocket).
 Class<? extends SelectionKeyHandler> getPreferredSelectionKeyHandler()
          Get the preffered SelectionKeyHandler implementation for this SelectorHandler.
 ProtocolChainInstanceHandler getProtocolChainInstanceHandler()
          Return the ProtocolChainInstanceHandler
 SelectionKeyHandler getSelectionKeyHandler()
          Get the SelectionKeyHandler associated with this SelectorHandler.
 Selector getSelector()
          Gets the underlying selector.
 long getSelectTimeout()
           
 int getServerTimeout()
           
 int getSocketTimeout()
           
 int getSsBackLog()
           
 StateHolder<State> getStateHolder()
          Gets StateHolder for this object
protected  void initOpRegistriesIfRequired()
          Initializes SelectionKey operation registries
protected  void invokeAsyncQueueReader(Context context)
          Invoke a AsyncQueueReader
protected  void invokeAsyncQueueWriter(Context context)
          Invoke a AsyncQueueWriter
protected  void invokeCallbackHandler(CallbackHandler callbackHandler, Context context)
          Invoke a CallbackHandler via a Context instance.
 boolean isOpen()
          Is the Selector open.
 boolean isReuseAddress()
           
 boolean isTcpNoDelay()
          Return the tcpNoDelay value used by the underlying accepted Sockets.
 Set<SelectionKey> keys()
          Return the set of SelectionKey registered on this Selector.
 boolean onAcceptInterest(SelectionKey key, Context ctx)
          Handle OP_ACCEPT.
 boolean onConnectInterest(SelectionKey key, Context ctx)
          Handle OP_CONNECT.
protected  void onConnectOp(Context ctx, SelectionKeyOP.ConnectSelectionKeyOP selectionKeyOp)
          Handle new OP_CONNECT ops.
 boolean onReadInterest(SelectionKey key, Context ctx)
          Handle OP_READ.
protected  void onReadOp(SelectionKeyOP selectionKeyOp)
          Handle new OP_READ ops.
 boolean onWriteInterest(SelectionKey key, Context ctx)
          Handle OP_WRITE.
protected  void onWriteOp(SelectionKeyOP selectionKeyOp)
          Handle new OP_WRITE ops.
 void pause()
          Pause this SelectorHandler
 Pipeline pipeline()
          Return the Pipeline used to execute this SelectorHandler's SelectionKey ops
protected  Context pollContext(Context serverContext, SelectionKey key, Context.OpType opType)
          Polls Context from pool and initializes it.
 void postSelect(Context ctx)
          Invoked after Selector.select().
 void preSelect(Context ctx)
          Before invoking Selector.select(), make sure the ServerScoketChannel has been created.
protected  void processPendingOperations(Context ctx)
           
 Controller.Protocol protocol()
          A token decribing the protocol supported by an implementation of this interface
 void register(SelectableChannel channel, int ops)
          Register the SelectableChannel on the Selector.
 void register(SelectionKey key, int ops)
          Register a SelectionKey to this Selector.
 void releaseConnectorHandler(ConnectorHandler connectorHandler)
          Release a ConnectorHandler.
 Object removeAttribute(String key)
          Remove a key/value object.
 void resume()
          Resume this SelectorHandler
 Set<SelectionKey> select(Context ctx)
          Execute the Selector.select(...) operations.
 void setAttribute(String key, Object value)
          Set a key/value object.
 void setAttributes(Map<String,Object> attributes)
          Set a Map of attribute name/value pairs.
 void setInet(InetAddress inet)
           
 void setLinger(int linger)
           
 void setLogger(Logger logger)
           
 void setPipeline(Pipeline pipeline)
          Set the Pipeline used to execute this SelectorHandler's SelectionKey ops
 void setPort(int port)
           
 void setProtocolChainInstanceHandler(ProtocolChainInstanceHandler instanceHandler)
          Set the ProtocolChainInstanceHandler to use for creating instance of ProtocolChain.
 void setReuseAddress(boolean reuseAddress)
           
 void setSelectionKeyHandler(SelectionKeyHandler selectionKeyHandler)
          Set SelectionKeyHandler associated with this SelectorHandler.
 void setSelector(Selector selector)
          Sets the underlying Selector
 void setSelectTimeout(long selectTimeout)
           
 void setServerTimeout(int serverTimeout)
           
 void setSocketTimeout(int socketTimeout)
           
 void setSsBackLog(int ssBackLog)
           
 void setTcpNoDelay(boolean tcpNoDelay)
          Enable (true) or disable (false) the underlying Socket's tcpNoDelay.
 void shutdown()
          Shuntdown this instance by closing its Selector and associated channels.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

connectorInstanceHandler

protected ConnectorInstanceHandler connectorInstanceHandler
The ConnectorInstanceHandler used to return a new or pooled ConnectorHandler


opToRegister

protected ConcurrentLinkedQueue<SelectionKeyOP> opToRegister
The list of SelectionKeyOP to register next time the Selector.select is invoked.


tcpNoDelay

protected boolean tcpNoDelay
The socket tcpDelay. Default value for tcpNoDelay is disabled (set to true).


reuseAddress

protected boolean reuseAddress
The socket reuseAddress


linger

protected int linger
The socket linger.


socketTimeout

protected int socketTimeout
The socket time out


logger

protected Logger logger

serverTimeout

protected int serverTimeout
The server socket time out


inet

protected InetAddress inet
The inet address to use when binding.


port

protected int port
The default TCP port.


serverSocket

protected ServerSocket serverSocket
The ServerSocket instance.


serverSocketChannel

protected ServerSocketChannel serverSocketChannel
The ServerSocketChannel.


selector

protected Selector selector
The single Selector.


selectTimeout

protected long selectTimeout
The Selector time out.


ssBackLog

protected int ssBackLog
Server socket backlog.


isClient

protected boolean isClient
Is this used for client only or client/server operation.


selectionKeyHandler

protected SelectionKeyHandler selectionKeyHandler
The SelectionKeyHandler associated with this SelectorHandler.


instanceHandler

protected ProtocolChainInstanceHandler instanceHandler
The ProtocolChainInstanceHandler used by this instance. If not set, and instance of the DefaultInstanceHandler will be created.


pipeline

protected Pipeline pipeline
The Pipeline used by this instance. If null - Controller's Pipeline will be used


asyncQueueWriter

protected AsyncQueueWriter asyncQueueWriter
AsyncQueueWriter


asyncQueueReader

protected AsyncQueueReader asyncQueueReader
AsyncQueueWriter


attributes

protected Map<String,Object> attributes
Attributes, associated with the SelectorHandler instance


stateHolder

protected StateHolder<State> stateHolder
This SelectorHandler StateHolder, which is shared among SelectorHandler and its clones


isShutDown

protected AtomicBoolean isShutDown
Flag, which shows whether shutdown was called for this SelectorHandler

Constructor Detail

TCPSelectorHandler

public TCPSelectorHandler()

TCPSelectorHandler

public TCPSelectorHandler(boolean isClient)
Create a TCPSelectorHandler only used with ConnectorHandler.

Parameters:
isClient - true if this SelectorHandler is only used to handle ConnectorHandler.
Method Detail

copyTo

public void copyTo(Copyable copy)
Description copied from interface: Copyable
Copies current object content to copy object

Specified by:
copyTo in interface Copyable
Parameters:
copy - represents target object, where current object's content will be copied

keys

public Set<SelectionKey> keys()
Return the set of SelectionKey registered on this Selector.

Specified by:
keys in interface SelectorHandler
Returns:
Set of SelectionKey

isOpen

public boolean isOpen()
Is the Selector open.

Specified by:
isOpen in interface SelectorHandler
Returns:
true / false

preSelect

public void preSelect(Context ctx)
               throws IOException
Before invoking Selector.select(), make sure the ServerScoketChannel has been created. If true, then register all SelectionKey to the Selector.

Specified by:
preSelect in interface SelectorHandler
Parameters:
ctx - Context
Throws:
IOException

processPendingOperations

protected void processPendingOperations(Context ctx)
                                 throws IOException
Throws:
IOException

onReadOp

protected void onReadOp(SelectionKeyOP selectionKeyOp)
                 throws ClosedChannelException
Handle new OP_READ ops.

Throws:
ClosedChannelException

onWriteOp

protected void onWriteOp(SelectionKeyOP selectionKeyOp)
                  throws ClosedChannelException
Handle new OP_WRITE ops.

Throws:
ClosedChannelException

onConnectOp

protected void onConnectOp(Context ctx,
                           SelectionKeyOP.ConnectSelectionKeyOP selectionKeyOp)
                    throws IOException
Handle new OP_CONNECT ops.

Throws:
IOException

select

public Set<SelectionKey> select(Context ctx)
                         throws IOException
Execute the Selector.select(...) operations.

Specified by:
select in interface SelectorHandler
Parameters:
ctx - Context
Returns:
Set of Context
Throws:
IOException

postSelect

public void postSelect(Context ctx)
Invoked after Selector.select().

Specified by:
postSelect in interface SelectorHandler
Parameters:
ctx - Context

register

public void register(SelectionKey key,
                     int ops)
Register a SelectionKey to this Selector.

Specified by:
register in interface SelectorHandler
ops - interested operations

register

public void register(SelectableChannel channel,
                     int ops)
Description copied from interface: SelectorHandler
Register the SelectableChannel on the Selector.

Specified by:
register in interface SelectorHandler
ops - interested operations

connect

protected void connect(SocketAddress remoteAddress,
                       SocketAddress localAddress,
                       CallbackHandler callBackHandler)
                throws IOException
Register a CallBackHandler to this Selector.

Parameters:
remoteAddress - remote address to connect
localAddress - local address to bin
callBackHandler - CallbackHandler
Throws:
IOException

pause

public void pause()
Pause this SelectorHandler

Specified by:
pause in interface SelectorHandler

resume

public void resume()
Resume this SelectorHandler

Specified by:
resume in interface SelectorHandler

getStateHolder

public StateHolder<State> getStateHolder()
Gets StateHolder for this object

Specified by:
getStateHolder in interface SupportStateHolder<State>
Returns:
StateHolder

shutdown

public void shutdown()
Shuntdown this instance by closing its Selector and associated channels.

Specified by:
shutdown in interface SelectorHandler

acceptWithoutRegistration

public SelectableChannel acceptWithoutRegistration(SelectionKey key)
                                            throws IOException
Accepts connection, without registering it for reading or writing

Specified by:
acceptWithoutRegistration in interface SelectorHandler
Returns:
accepted SelectableChannel
Throws:
IOException

onAcceptInterest

public boolean onAcceptInterest(SelectionKey key,
                                Context ctx)
                         throws IOException
Handle OP_ACCEPT.

Specified by:
onAcceptInterest in interface SelectorHandler
Parameters:
ctx - Context
key - SelectionKey
Returns:
always returns false
Throws:
IOException

onReadInterest

public boolean onReadInterest(SelectionKey key,
                              Context ctx)
                       throws IOException
Handle OP_READ.

Specified by:
onReadInterest in interface SelectorHandler
Parameters:
ctx - Context
key - SelectionKey
Returns:
false if handled by a CallbackHandler, otherwise true
Throws:
IOException

onWriteInterest

public boolean onWriteInterest(SelectionKey key,
                               Context ctx)
                        throws IOException
Handle OP_WRITE.

Specified by:
onWriteInterest in interface SelectorHandler
Parameters:
key - SelectionKey
ctx - Context
Returns:
true if and only if the ProtocolChain must be invoked after executing this method.
Throws:
IOException

onConnectInterest

public boolean onConnectInterest(SelectionKey key,
                                 Context ctx)
                          throws IOException
Handle OP_CONNECT.

Specified by:
onConnectInterest in interface SelectorHandler
Parameters:
key - SelectionKey
ctx - Context
Returns:
true if and only if the ProtocolChain must be invoked after executing this method.
Throws:
IOException

invokeCallbackHandler

protected void invokeCallbackHandler(CallbackHandler callbackHandler,
                                     Context context)
                              throws IOException
Invoke a CallbackHandler via a Context instance.

Parameters:
context - Context
Throws:
IOException

invokeAsyncQueueReader

protected void invokeAsyncQueueReader(Context context)
                               throws IOException
Invoke a AsyncQueueReader

Parameters:
context - Context
Throws:
IOException

invokeAsyncQueueWriter

protected void invokeAsyncQueueWriter(Context context)
                               throws IOException
Invoke a AsyncQueueWriter

Parameters:
context - Context
Throws:
IOException

acquireConnectorHandler

public ConnectorHandler acquireConnectorHandler()
Return an instance of the default ConnectorHandler, which is the TCPConnectorHandler

Specified by:
acquireConnectorHandler in interface SelectorHandler
Returns:
ConnectorHandler

releaseConnectorHandler

public void releaseConnectorHandler(ConnectorHandler connectorHandler)
Release a ConnectorHandler.

Specified by:
releaseConnectorHandler in interface SelectorHandler
Parameters:
connectorHandler - ConnectorHandler

protocol

public Controller.Protocol protocol()
A token decribing the protocol supported by an implementation of this interface

Specified by:
protocol in interface SelectorHandler
Returns:
SelectorHandler supported protocol

initOpRegistriesIfRequired

protected void initOpRegistriesIfRequired()
Initializes SelectionKey operation registries


configureChannel

public void configureChannel(SelectableChannel channel)
                      throws IOException
Configure the channel operations.

Specified by:
configureChannel in interface SelectorHandler
Parameters:
channel - SelectableChannel to configure
Throws:
IOException - on possible configuration related error

getSelector

public final Selector getSelector()
Description copied from interface: SelectorHandler
Gets the underlying selector.

Specified by:
getSelector in interface SelectorHandler
Returns:
underlying Selector

setSelector

public final void setSelector(Selector selector)
Description copied from interface: SelectorHandler
Sets the underlying Selector

Specified by:
setSelector in interface SelectorHandler
Parameters:
selector - underlying Selector

getAsyncQueueReader

public AsyncQueueReader getAsyncQueueReader()
Returns AsyncQueueReader associated with this SelectorHandler. Method will return null, if this SelectorHandler is not running.

Specified by:
getAsyncQueueReader in interface SelectorHandler
Returns:
AsyncQueueReader

getAsyncQueueWriter

public AsyncQueueWriter getAsyncQueueWriter()
Returns AsyncQueueWriter associated with this SelectorHandler. Method will return null, if this SelectorHandler is not running.

Specified by:
getAsyncQueueWriter in interface SelectorHandler
Returns:
AsyncQuqueWriter

getSelectTimeout

public long getSelectTimeout()

setSelectTimeout

public void setSelectTimeout(long selectTimeout)

getServerTimeout

public int getServerTimeout()

setServerTimeout

public void setServerTimeout(int serverTimeout)

getInet

public InetAddress getInet()

setInet

public void setInet(InetAddress inet)

getPortLowLevel

public int getPortLowLevel()
Returns port number SelectorHandler is listening on Similar to getPort(), but getting port number directly from connection (ServerSocket, DatagramSocket). So if default port number 0 was set during initialization, then getPort() will return 0, but getPortLowLevel() will return port number assigned by OS.

Returns:
port number or -1 if SelectorHandler was not initialized for accepting connections.

getPort

public int getPort()

setPort

public void setPort(int port)

getSsBackLog

public int getSsBackLog()

setSsBackLog

public void setSsBackLog(int ssBackLog)

isTcpNoDelay

public boolean isTcpNoDelay()
Return the tcpNoDelay value used by the underlying accepted Sockets. Also see setTcpNoDelay(boolean tcpNoDelay)


setTcpNoDelay

public void setTcpNoDelay(boolean tcpNoDelay)
Enable (true) or disable (false) the underlying Socket's tcpNoDelay. Default value for tcpNoDelay is disabled (set to false). Disabled by default since enabling tcpNoDelay for most applications can cause packets to appear to arrive in a fragmented fashion where it takes multiple OP_READ events (i.e. multiple calls to read small messages). The common behaviour seen when this occurs is that often times a small number of bytes, as small as 1 byte at a time is read per OP_READ event dispatch. This results in a large number of system calls to read(), system calls to enable and disable interest ops and potentially a large number of thread context switches between a thread doing the Select(ing) and a worker thread doing the read. The Connector side should also set tcpNoDelay the same as it is set here whenever possible.


getLinger

public int getLinger()

setLinger

public void setLinger(int linger)

getSocketTimeout

public int getSocketTimeout()

setSocketTimeout

public void setSocketTimeout(int socketTimeout)

getLogger

public Logger getLogger()

setLogger

public void setLogger(Logger logger)

isReuseAddress

public boolean isReuseAddress()

setReuseAddress

public void setReuseAddress(boolean reuseAddress)

pipeline

public Pipeline pipeline()
Return the Pipeline used to execute this SelectorHandler's SelectionKey ops

Specified by:
pipeline in interface SelectorHandler
Returns:
The pipeline to use, or null if the Controller's Pipeline should be used.

setPipeline

public void setPipeline(Pipeline pipeline)
Set the Pipeline used to execute this SelectorHandler's SelectionKey ops

Specified by:
setPipeline in interface SelectorHandler

getPreferredSelectionKeyHandler

public Class<? extends SelectionKeyHandler> getPreferredSelectionKeyHandler()
Get the preffered SelectionKeyHandler implementation for this SelectorHandler.

Specified by:
getPreferredSelectionKeyHandler in interface SelectorHandler

getSelectionKeyHandler

public SelectionKeyHandler getSelectionKeyHandler()
Get the SelectionKeyHandler associated with this SelectorHandler.

Specified by:
getSelectionKeyHandler in interface SelectorHandler

setSelectionKeyHandler

public void setSelectionKeyHandler(SelectionKeyHandler selectionKeyHandler)
Set SelectionKeyHandler associated with this SelectorHandler.

Specified by:
setSelectionKeyHandler in interface SelectorHandler

setProtocolChainInstanceHandler

public void setProtocolChainInstanceHandler(ProtocolChainInstanceHandler instanceHandler)
Set the ProtocolChainInstanceHandler to use for creating instance of ProtocolChain.

Specified by:
setProtocolChainInstanceHandler in interface SelectorHandler

getProtocolChainInstanceHandler

public ProtocolChainInstanceHandler getProtocolChainInstanceHandler()
Return the ProtocolChainInstanceHandler

Specified by:
getProtocolChainInstanceHandler in interface SelectorHandler

closeChannel

public void closeChannel(SelectableChannel channel)
Closes SelectableChannel

Specified by:
closeChannel in interface SelectorHandler

pollContext

protected Context pollContext(Context serverContext,
                              SelectionKey key,
                              Context.OpType opType)
Polls Context from pool and initializes it.

Parameters:
serverContext - Controller context
key - SelectionKey
Returns:
Context

getConnectorInstanceHandlerDelegate

protected Callable<ConnectorHandler> getConnectorInstanceHandlerDelegate()
Return factory object, which knows how to create ConnectorInstanceHandler corresponding to the protocol

Returns:
factory

removeAttribute

public Object removeAttribute(String key)
Remove a key/value object. Method is not thread safe

Specified by:
removeAttribute in interface AttributeHolder
Parameters:
key - - name of an attribute
Returns:
attribute which has been removed

setAttribute

public void setAttribute(String key,
                         Object value)
Set a key/value object. Method is not thread safe

Specified by:
setAttribute in interface AttributeHolder
Parameters:
key - - name of an attribute
value - - value of named attribute

getAttribute

public Object getAttribute(String key)
Return an object based on a key. Method is not thread safe

Specified by:
getAttribute in interface AttributeHolder
Parameters:
key - - name of an attribute
Returns:
- attribute value for the key, null if key does not exist in attributes

setAttributes

public void setAttributes(Map<String,Object> attributes)
Set a Map of attribute name/value pairs. Old AttributeHolder values will not be available. Later changes of this Map will lead to changes to the current AttributeHolder.

Specified by:
setAttributes in interface AttributeHolder
Parameters:
attributes - - map of name/value pairs

getAttributes

public Map<String,Object> getAttributes()
Return a Map of attribute name/value pairs. Updates, performed on the returned Map will be reflected in this AttributeHolder

Specified by:
getAttributes in interface AttributeHolder
Returns:
- Map of attribute name/value pairs


Copyright © 2011 SUN Microsystems. All Rights Reserved.