Package org.apache.mina.core.polling
Class AbstractPollingIoAcceptor<S extends AbstractIoSession,H>
- java.lang.Object
-
- org.apache.mina.core.service.AbstractIoService
-
- org.apache.mina.core.service.AbstractIoAcceptor
-
- org.apache.mina.core.polling.AbstractPollingIoAcceptor<S,H>
-
- Type Parameters:
H- The type of IoHandlerS- The type of IoSession
- All Implemented Interfaces:
IoAcceptor,IoService
- Direct Known Subclasses:
AprSocketAcceptor,NioSocketAcceptor
public abstract class AbstractPollingIoAcceptor<S extends AbstractIoSession,H> extends AbstractIoAcceptor
A base class for implementing transport using a polling strategy. The underlying sockets will be checked in an active loop and woke up when an socket needed to be processed. This class handle the logic behind binding, accepting and disposing the server sockets. AnExecutorwill be used for running client accepting and anAbstractPollingIoProcessorwill be used for processing client I/O operations like reading, writing and closing. All the low level methods for binding, accepting, closing need to be provided by the subclassing implementation.- See Also:
for a example of implementation
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description private classAbstractPollingIoAcceptor.AcceptorThis class is called by the startupAcceptor() method and is placed into a NamePreservingRunnable class.-
Nested classes/interfaces inherited from class org.apache.mina.core.service.AbstractIoAcceptor
AbstractIoAcceptor.AcceptorOperationFuture
-
Nested classes/interfaces inherited from class org.apache.mina.core.service.AbstractIoService
AbstractIoService.ServiceOperationFuture
-
-
Field Summary
Fields Modifier and Type Field Description private java.util.concurrent.atomic.AtomicReference<AbstractPollingIoAcceptor.Acceptor>acceptorRefThe thread responsible of accepting incoming requestsprotected intbacklogDefine the number of socket that can wait to be accepted.private java.util.Map<java.net.SocketAddress,H>boundHandlesprivate java.util.Queue<AbstractIoAcceptor.AcceptorOperationFuture>cancelQueueprivate booleancreatedProcessorprivate AbstractIoService.ServiceOperationFuturedisposalFutureprivate java.util.concurrent.SemaphorelockA lock used to protect the selector to be waked up before it's createdprivate IoProcessor<S>processorprivate java.util.Queue<AbstractIoAcceptor.AcceptorOperationFuture>registerQueueprotected booleanreuseAddressprivate booleanselectableA flag set when the acceptor has been created and initialized-
Fields inherited from class org.apache.mina.core.service.AbstractIoAcceptor
bindLock
-
Fields inherited from class org.apache.mina.core.service.AbstractIoService
disposalLock, LOGGER, sessionConfig
-
-
Constructor Summary
Constructors Modifier Constructor Description protectedAbstractPollingIoAcceptor(IoSessionConfig sessionConfig, java.lang.Class<? extends IoProcessor<S>> processorClass)Constructor forAbstractPollingIoAcceptor.protectedAbstractPollingIoAcceptor(IoSessionConfig sessionConfig, java.lang.Class<? extends IoProcessor<S>> processorClass, int processorCount)Constructor forAbstractPollingIoAcceptor.protectedAbstractPollingIoAcceptor(IoSessionConfig sessionConfig, java.lang.Class<? extends IoProcessor<S>> processorClass, int processorCount, java.nio.channels.spi.SelectorProvider selectorProvider)Constructor forAbstractPollingIoAcceptor.protectedAbstractPollingIoAcceptor(IoSessionConfig sessionConfig, java.util.concurrent.Executor executor, IoProcessor<S> processor)Constructor forAbstractPollingIoAcceptor.privateAbstractPollingIoAcceptor(IoSessionConfig sessionConfig, java.util.concurrent.Executor executor, IoProcessor<S> processor, boolean createdProcessor, java.nio.channels.spi.SelectorProvider selectorProvider)Constructor forAbstractPollingIoAcceptor.protectedAbstractPollingIoAcceptor(IoSessionConfig sessionConfig, IoProcessor<S> processor)Constructor forAbstractPollingIoAcceptor.
-
Method Summary
All Methods Instance Methods Abstract Methods Concrete Methods Modifier and Type Method Description protected abstract Saccept(IoProcessor<S> processor, H handle)Accept a client connection for a server socket and return a newIoSessionassociated with the givenIoProcessorprotected java.util.Set<java.net.SocketAddress>bindInternal(java.util.List<? extends java.net.SocketAddress> localAddresses)Starts the acceptor, and register the given addressesprotected voidbindRequestAdded()Invoked when a bind request has been registered for processing.protected abstract voidclose(H handle)Close a server socket.protected abstract voiddestroy()Destroy the polling system, will be called when thisIoAcceptorimplementation will be disposed.protected voiddispose0()Implement this method to release any acquired resources.intgetBacklog()SocketSessionConfiggetSessionConfig()protected voidhandleUnbound(java.util.Collection<AbstractIoAcceptor.AcceptorOperationFuture> unboundFutures)Processes the futures for executed unbindings, marking all futures as done.protected booleanhasUnbindings()Tells whether there are pending unbindings.protected abstract voidinit()Initialize the polling system, will be called at construction time.protected abstract voidinit(java.nio.channels.spi.SelectorProvider selectorProvider)Initialize the polling system, will be called at construction time.booleanisReuseAddress()protected abstract java.net.SocketAddresslocalAddress(H handle)Get the local address associated with a given server socketIoSessionnewSession(java.net.SocketAddress remoteAddress, java.net.SocketAddress localAddress)(Optional) Returns anIoSessionthat is bound to the specifiedlocalAddressand the specifiedremoteAddresswhich reuses the local address that is already bound by this service.protected abstract Hopen(java.net.SocketAddress localAddress)Open a server socket for a given local address.protected voidprocessHandles(java.util.Iterator<H> handles)Handles new incoming connections by accepting the connections and creating new sessions for them.protected abstract intselect()Check for acceptable connections, interrupt when at least a server is ready for accepting.protected abstract java.util.Iterator<H>selectedHandles()Iteratorfor the set of server sockets found with acceptable incoming connections during the lastselect()call.voidsetBacklog(int backlog)Sets the Backlog parametervoidsetReuseAddress(boolean reuseAddress)Set the Reuse Address flagprivate voidstartupAcceptor()This method is called by the doBind() and doUnbind() methods.protected voidunbind0(java.util.List<? extends java.net.SocketAddress> localAddresses)Implement this method to perform the actual unbind operation.protected abstract voidwakeup()Interrupt theselect()method.-
Methods inherited from class org.apache.mina.core.service.AbstractIoAcceptor
bind, bind, bind, bind, bind, getDefaultLocalAddress, getDefaultLocalAddresses, getLocalAddress, getLocalAddresses, isCloseOnDeactivation, setCloseOnDeactivation, setDefaultLocalAddress, setDefaultLocalAddresses, setDefaultLocalAddresses, setDefaultLocalAddresses, toString, unbind, unbind, unbind, unbind
-
Methods inherited from class org.apache.mina.core.service.AbstractIoService
addListener, broadcast, dispose, dispose, executeWorker, executeWorker, finishSessionInitialization0, getActivationTime, getFilterChain, getFilterChainBuilder, getHandler, getListeners, getManagedSessionCount, getManagedSessions, getScheduledWriteBytes, getScheduledWriteMessages, getSessionDataStructureFactory, getStatistics, initSession, isActive, isDisposed, isDisposing, removeListener, setFilterChainBuilder, setHandler, setSessionDataStructureFactory
-
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
-
Methods inherited from interface org.apache.mina.core.service.IoService
addListener, broadcast, dispose, dispose, getActivationTime, getFilterChain, getFilterChainBuilder, getHandler, getManagedSessionCount, getManagedSessions, getScheduledWriteBytes, getScheduledWriteMessages, getSessionDataStructureFactory, getStatistics, getTransportMetadata, isActive, isDisposed, isDisposing, removeListener, setFilterChainBuilder, setHandler, setSessionDataStructureFactory
-
-
-
-
Field Detail
-
lock
private final java.util.concurrent.Semaphore lock
A lock used to protect the selector to be waked up before it's created
-
processor
private final IoProcessor<S extends AbstractIoSession> processor
-
createdProcessor
private final boolean createdProcessor
-
registerQueue
private final java.util.Queue<AbstractIoAcceptor.AcceptorOperationFuture> registerQueue
-
cancelQueue
private final java.util.Queue<AbstractIoAcceptor.AcceptorOperationFuture> cancelQueue
-
boundHandles
private final java.util.Map<java.net.SocketAddress,H> boundHandles
-
disposalFuture
private final AbstractIoService.ServiceOperationFuture disposalFuture
-
selectable
private volatile boolean selectable
A flag set when the acceptor has been created and initialized
-
acceptorRef
private java.util.concurrent.atomic.AtomicReference<AbstractPollingIoAcceptor.Acceptor> acceptorRef
The thread responsible of accepting incoming requests
-
reuseAddress
protected boolean reuseAddress
-
backlog
protected int backlog
Define the number of socket that can wait to be accepted. Default to 50 (as in the SocketServer default).
-
-
Constructor Detail
-
AbstractPollingIoAcceptor
protected AbstractPollingIoAcceptor(IoSessionConfig sessionConfig, java.lang.Class<? extends IoProcessor<S>> processorClass)
Constructor forAbstractPollingIoAcceptor. You need to provide a default session configuration, a class ofIoProcessorwhich will be instantiated in aSimpleIoProcessorPoolfor better scaling in multiprocessor systems. The default pool size will be used.- Parameters:
sessionConfig- the default configuration for the managedIoSessionprocessorClass- aClassofIoProcessorfor the associatedIoSessiontype.- See Also:
SimpleIoProcessorPool
-
AbstractPollingIoAcceptor
protected AbstractPollingIoAcceptor(IoSessionConfig sessionConfig, java.lang.Class<? extends IoProcessor<S>> processorClass, int processorCount)
Constructor forAbstractPollingIoAcceptor. You need to provide a default session configuration, a class ofIoProcessorwhich will be instantiated in aSimpleIoProcessorPoolfor using multiple thread for better scaling in multiprocessor systems.- Parameters:
sessionConfig- the default configuration for the managedIoSessionprocessorClass- aClassofIoProcessorfor the associatedIoSessiontype.processorCount- the amount of processor to instantiate for the pool- See Also:
SimpleIoProcessorPool
-
AbstractPollingIoAcceptor
protected AbstractPollingIoAcceptor(IoSessionConfig sessionConfig, java.lang.Class<? extends IoProcessor<S>> processorClass, int processorCount, java.nio.channels.spi.SelectorProvider selectorProvider)
Constructor forAbstractPollingIoAcceptor. You need to provide a default session configuration, a class ofIoProcessorwhich will be instantiated in aSimpleIoProcessorPoolfor using multiple thread for better scaling in multiprocessor systems.- Parameters:
sessionConfig- the default configuration for the managedIoSessionprocessorClass- aClassofIoProcessorfor the associatedIoSessiontype.processorCount- the amount of processor to instantiate for the poolselectorProvider- The SelectorProvider to use- See Also:
SimpleIoProcessorPool
-
AbstractPollingIoAcceptor
protected AbstractPollingIoAcceptor(IoSessionConfig sessionConfig, IoProcessor<S> processor)
Constructor forAbstractPollingIoAcceptor. You need to provide a default session configuration, a defaultExecutorwill be created usingExecutors.newCachedThreadPool().- Parameters:
sessionConfig- the default configuration for the managedIoSessionprocessor- theIoProcessorfor processing theIoSessionof this transport, triggering events to the boundIoHandlerand processing the chains ofIoFilter- See Also:
AbstractIoService
-
AbstractPollingIoAcceptor
protected AbstractPollingIoAcceptor(IoSessionConfig sessionConfig, java.util.concurrent.Executor executor, IoProcessor<S> processor)
Constructor forAbstractPollingIoAcceptor. You need to provide a default session configuration and anExecutorfor handling I/O events. If a nullExecutoris provided, a default one will be created usingExecutors.newCachedThreadPool().- Parameters:
sessionConfig- the default configuration for the managedIoSessionexecutor- theExecutorused for handling asynchronous execution of I/O events. Can benull.processor- theIoProcessorfor processing theIoSessionof this transport, triggering events to the boundIoHandlerand processing the chains ofIoFilter- See Also:
AbstractIoService(IoSessionConfig, Executor)
-
AbstractPollingIoAcceptor
private AbstractPollingIoAcceptor(IoSessionConfig sessionConfig, java.util.concurrent.Executor executor, IoProcessor<S> processor, boolean createdProcessor, java.nio.channels.spi.SelectorProvider selectorProvider)
Constructor forAbstractPollingIoAcceptor. You need to provide a default session configuration and anExecutorfor handling I/O events. If a nullExecutoris provided, a default one will be created usingExecutors.newCachedThreadPool().- Parameters:
sessionConfig- the default configuration for the managedIoSessionexecutor- theExecutorused for handling asynchronous execution of I/O events. Can benull.processor- theIoProcessorfor processing theIoSessionof this transport, triggering events to the boundIoHandlerand processing the chains ofIoFiltercreatedProcessor- tagging the processor as automatically created, so it will be automatically disposed- See Also:
#AbstractIoService(IoSessionConfig, Executor)
-
-
Method Detail
-
init
protected abstract void init() throws java.lang.ExceptionInitialize the polling system, will be called at construction time.- Throws:
java.lang.Exception- any exception thrown by the underlying system calls
-
init
protected abstract void init(java.nio.channels.spi.SelectorProvider selectorProvider) throws java.lang.ExceptionInitialize the polling system, will be called at construction time.- Parameters:
selectorProvider- The Selector Provider that will be used by this polling acceptor- Throws:
java.lang.Exception- any exception thrown by the underlying system calls
-
destroy
protected abstract void destroy() throws java.lang.ExceptionDestroy the polling system, will be called when thisIoAcceptorimplementation will be disposed.- Throws:
java.lang.Exception- any exception thrown by the underlying systems calls
-
select
protected abstract int select() throws java.lang.ExceptionCheck for acceptable connections, interrupt when at least a server is ready for accepting. All the ready server socket descriptors need to be returned byselectedHandles()- Returns:
- The number of sockets having got incoming client
- Throws:
java.lang.Exception- any exception thrown by the underlying systems calls
-
wakeup
protected abstract void wakeup()
Interrupt theselect()method. Used when the poll set need to be modified.
-
selectedHandles
protected abstract java.util.Iterator<H> selectedHandles()
Iteratorfor the set of server sockets found with acceptable incoming connections during the lastselect()call.- Returns:
- the list of server handles ready
-
open
protected abstract H open(java.net.SocketAddress localAddress) throws java.lang.Exception
Open a server socket for a given local address.- Parameters:
localAddress- the associated local address- Returns:
- the opened server socket
- Throws:
java.lang.Exception- any exception thrown by the underlying systems calls
-
localAddress
protected abstract java.net.SocketAddress localAddress(H handle) throws java.lang.Exception
Get the local address associated with a given server socket- Parameters:
handle- the server socket- Returns:
- the local
SocketAddressassociated with this handle - Throws:
java.lang.Exception- any exception thrown by the underlying systems calls
-
accept
protected abstract S accept(IoProcessor<S> processor, H handle) throws java.lang.Exception
Accept a client connection for a server socket and return a newIoSessionassociated with the givenIoProcessor- Parameters:
processor- theIoProcessorto associate with theIoSessionhandle- the server handle- Returns:
- the created
IoSession - Throws:
java.lang.Exception- any exception thrown by the underlying systems calls
-
close
protected abstract void close(H handle) throws java.lang.Exception
Close a server socket.- Parameters:
handle- the server socket- Throws:
java.lang.Exception- any exception thrown by the underlying systems calls
-
dispose0
protected void dispose0() throws java.lang.ExceptionImplement this method to release any acquired resources. This method is invoked only once byAbstractIoService.dispose().- Specified by:
dispose0in classAbstractIoService- Throws:
java.lang.Exception- If the dispose failed
-
bindRequestAdded
protected void bindRequestAdded()
Invoked when a bind request has been registered for processing. The default implementation does nothing.
-
bindInternal
protected final java.util.Set<java.net.SocketAddress> bindInternal(java.util.List<? extends java.net.SocketAddress> localAddresses) throws java.lang.ExceptionStarts the acceptor, and register the given addresses- Specified by:
bindInternalin classAbstractIoAcceptor- Parameters:
localAddresses- The address to bind to- Returns:
- the
Setof the local addresses which is bound actually - Throws:
java.lang.Exception- If the bind failed
-
startupAcceptor
private void startupAcceptor() throws java.lang.InterruptedExceptionThis method is called by the doBind() and doUnbind() methods. If the acceptor is null, the acceptor object will be created and kicked off by the executor. If the acceptor object is null, probably already created and this class is now working, then nothing will happen and the method will just return.- Throws:
java.lang.InterruptedException
-
unbind0
protected final void unbind0(java.util.List<? extends java.net.SocketAddress> localAddresses) throws java.lang.ExceptionImplement this method to perform the actual unbind operation.- Specified by:
unbind0in classAbstractIoAcceptor- Parameters:
localAddresses- The address to unbind from- Throws:
java.lang.Exception- If the unbind failed
-
processHandles
protected void processHandles(java.util.Iterator<H> handles) throws java.lang.Exception
Handles new incoming connections by accepting the connections and creating new sessions for them.- Parameters:
handles- the connection handles to accept and create new sessions for- Throws:
java.lang.Exception- on errors
-
hasUnbindings
protected boolean hasUnbindings()
Tells whether there are pending unbindings.- Returns:
trueif there are any unbindings pending;falseotherwise
-
handleUnbound
protected void handleUnbound(java.util.Collection<AbstractIoAcceptor.AcceptorOperationFuture> unboundFutures) throws java.lang.Exception
Processes the futures for executed unbindings, marking all futures as done.- Parameters:
unboundFutures- describing the unbindings- Throws:
java.lang.Exception- on errors
-
newSession
public final IoSession newSession(java.net.SocketAddress remoteAddress, java.net.SocketAddress localAddress)
(Optional) Returns anIoSessionthat is bound to the specifiedlocalAddressand the specifiedremoteAddresswhich reuses the local address that is already bound by this service.This operation is optional. Please throw
UnsupportedOperationExceptionif the transport type doesn't support this operation. This operation is usually implemented for connectionless transport types.- Parameters:
remoteAddress- The remote address bound to the servicelocalAddress- The local address the session will be bound to- Returns:
- The session bound to the the given localAddress and remote address
-
getBacklog
public int getBacklog()
- Returns:
- the backLog
-
setBacklog
public void setBacklog(int backlog)
Sets the Backlog parameter- Parameters:
backlog- the backlog variable
-
isReuseAddress
public boolean isReuseAddress()
- Returns:
- the flag that sets the reuseAddress information
-
setReuseAddress
public void setReuseAddress(boolean reuseAddress)
Set the Reuse Address flag- Parameters:
reuseAddress- The flag to set
-
getSessionConfig
public SocketSessionConfig getSessionConfig()
- Returns:
- the default configuration of the new
IoSessions created by this service.
-
-