Package org.apache.mina.core.polling
Class AbstractPollingIoProcessor<S extends AbstractIoSession>
- java.lang.Object
-
- org.apache.mina.core.polling.AbstractPollingIoProcessor<S>
-
- Type Parameters:
S- the type of theIoSessionthis processor can handle
- All Implemented Interfaces:
IoProcessor<S>
- Direct Known Subclasses:
AprIoProcessor,NioProcessor
public abstract class AbstractPollingIoProcessor<S extends AbstractIoSession> extends java.lang.Object implements IoProcessor<S>
An abstract implementation ofIoProcessorwhich helps transport developers to write anIoProcessoreasily. This class is in charge of active polling a set ofIoSessionand trigger events when some I/O operation is possible.
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description private classAbstractPollingIoProcessor.ProcessorThe main loop.
-
Field Summary
Fields Modifier and Type Field Description private DefaultIoFuturedisposalFutureprivate java.lang.ObjectdisposalLockprivate booleandisposedprivate booleandisposingprivate java.util.concurrent.ExecutorexecutorThe executor to use when we need to start the inner Processorprivate java.util.Queue<S>flushingSessionsA queue used to store the sessions to be flushedprivate longlastIdleCheckTimeprivate static org.slf4j.LoggerLOGA logger for this classprivate java.util.Queue<S>newSessionsA Session queue containing the newly created sessionsprivate java.util.concurrent.atomic.AtomicReference<AbstractPollingIoProcessor.Processor>processorRefThe processor thread : it handles the incoming messagesprivate java.util.Queue<S>removingSessionsA queue used to store the sessions to be removedprivate static longSELECT_TIMEOUTA timeout used for the select, as we need to get out to deal with idle sessionsprivate static java.util.concurrent.ConcurrentHashMap<java.lang.Class<?>,java.util.concurrent.atomic.AtomicInteger>threadIdsA map containing the last Thread ID for each classprivate java.lang.StringthreadNameThis IoProcessor instance nameprivate java.util.Queue<S>trafficControllingSessionsA queue used to store the sessions which have a trafficControl to be updatedprotected java.util.concurrent.atomic.AtomicBooleanwakeupCalled
-
Constructor Summary
Constructors Modifier Constructor Description protectedAbstractPollingIoProcessor(java.util.concurrent.Executor executor)Create anAbstractPollingIoProcessorwith the givenExecutorfor handling I/Os events.
-
Method Summary
All Methods Instance Methods Abstract Methods Concrete Methods Modifier and Type Method Description voidadd(S session)Adds the specifiedsessionto the I/O processor so that the I/O processor starts to perform any I/O operations related with thesession.protected abstract java.util.Iterator<S>allSessions()protected abstract intallSessionsCount()Get the number ofIoSessionpolled by thisIoProcessorprotected abstract voiddestroy(S session)Destroy the underlying client socket handlevoiddispose()Releases any resources allocated by this processor.protected abstract voiddoDispose()Dispose the resources used by thisIoProcessorfor polling the client connections.voidflush(S session)Flushes the internal write request queue of the specifiedsession.protected abstract SessionStategetState(S session)Get the state of a session (One of OPENING, OPEN, CLOSING)protected abstract voidinit(S session)Initialize the polling of a session.protected abstract booleanisBrokenConnection()Check that the select() has not exited immediately just because of a broken connection.booleanisDisposed()booleanisDisposing()protected abstract booleanisInterestedInRead(S session)Tells if this session is registered for readingprotected abstract booleanisInterestedInWrite(S session)Tells if this session is registered for writingprotected abstract booleanisReadable(S session)Tells if the session ready for readingprotected abstract booleanisSelectorEmpty()Say if the list ofIoSessionpolled by thisIoProcessoris emptyprotected abstract booleanisWritable(S session)Tells if the session ready for writingprivate java.lang.StringnextThreadName()Compute the thread ID for this class instance.private voidread(S session)protected abstract intread(S session, IoBuffer buf)protected abstract voidregisterNewSelector()In the case we are using the java select() method, this method is used to trash the buggy selector and create a new one, registring all the sockets on it.voidremove(S session)Removes and closes the specifiedsessionfrom the I/O processor so that the I/O processor closes the connection associated with thesessionand releases any other related resources.private voidscheduleRemove(S session)protected abstract intselect()poll those sessions foreverprotected abstract intselect(long timeout)poll those sessions for the given timeoutprotected abstract java.util.Iterator<S>selectedSessions()protected abstract voidsetInterestedInRead(S session, boolean isInterested)Set the session to be informed when a read event should be processedprotected abstract voidsetInterestedInWrite(S session, boolean isInterested)Set the session to be informed when a write event should be processedprivate voidstartupProcessor()Starts the inner Processor, asking the executor to pick a thread in its pool.protected abstract inttransferFile(S session, FileRegion region, int length)Write a part of a file to aIoSession, if the underlying API isn't supporting system calls like sendfile(), you can throw aUnsupportedOperationExceptionso the file will be send using usualwrite(AbstractIoSession, IoBuffer, int)call.voidupdateTrafficControl(S session)Controls the traffic of the specifiedsessiondepending of theIoSession.isReadSuspended()andIoSession.isWriteSuspended()flagsvoidupdateTrafficMask(S session)Updates the traffic mask for a given sessionprotected abstract voidwakeup()Interrupt theselect(long)call.protected abstract intwrite(S session, IoBuffer buf, int length)Write a sequence of bytes to aIoSession, means to be called when a session was found ready for writing.voidwrite(S session, WriteRequest writeRequest)Writes the WriteRequest for the specifiedsession.
-
-
-
Field Detail
-
LOG
private static final org.slf4j.Logger LOG
A logger for this class
-
SELECT_TIMEOUT
private static final long SELECT_TIMEOUT
A timeout used for the select, as we need to get out to deal with idle sessions- See Also:
- Constant Field Values
-
threadIds
private static final java.util.concurrent.ConcurrentHashMap<java.lang.Class<?>,java.util.concurrent.atomic.AtomicInteger> threadIds
A map containing the last Thread ID for each class
-
threadName
private final java.lang.String threadName
This IoProcessor instance name
-
executor
private final java.util.concurrent.Executor executor
The executor to use when we need to start the inner Processor
-
newSessions
private final java.util.Queue<S extends AbstractIoSession> newSessions
A Session queue containing the newly created sessions
-
removingSessions
private final java.util.Queue<S extends AbstractIoSession> removingSessions
A queue used to store the sessions to be removed
-
flushingSessions
private final java.util.Queue<S extends AbstractIoSession> flushingSessions
A queue used to store the sessions to be flushed
-
trafficControllingSessions
private final java.util.Queue<S extends AbstractIoSession> trafficControllingSessions
A queue used to store the sessions which have a trafficControl to be updated
-
processorRef
private final java.util.concurrent.atomic.AtomicReference<AbstractPollingIoProcessor.Processor> processorRef
The processor thread : it handles the incoming messages
-
lastIdleCheckTime
private long lastIdleCheckTime
-
disposalLock
private final java.lang.Object disposalLock
-
disposing
private volatile boolean disposing
-
disposed
private volatile boolean disposed
-
disposalFuture
private final DefaultIoFuture disposalFuture
-
wakeupCalled
protected java.util.concurrent.atomic.AtomicBoolean wakeupCalled
-
-
Constructor Detail
-
AbstractPollingIoProcessor
protected AbstractPollingIoProcessor(java.util.concurrent.Executor executor)
Create anAbstractPollingIoProcessorwith the givenExecutorfor handling I/Os events.- Parameters:
executor- theExecutorfor handling I/O events
-
-
Method Detail
-
nextThreadName
private java.lang.String nextThreadName()
Compute the thread ID for this class instance. As we may have different classes, we store the last ID number into a Map associating the class name to the last assigned ID.- Returns:
- a name for the current thread, based on the class name and an incremental value, starting at 1.
-
isDisposing
public final boolean isDisposing()
- Specified by:
isDisposingin interfaceIoProcessor<S extends AbstractIoSession>- Returns:
trueif and if onlyIoProcessor.dispose()method has been called. Please note that this method will returntrueeven after all the related resources are released.
-
isDisposed
public final boolean isDisposed()
- Specified by:
isDisposedin interfaceIoProcessor<S extends AbstractIoSession>- Returns:
trueif and if only all resources of this processor have been disposed.
-
dispose
public final void dispose()
Releases any resources allocated by this processor. Please note that the resources might not be released as long as there are any sessions managed by this processor. Most implementations will close all sessions immediately and release the related resources.- Specified by:
disposein interfaceIoProcessor<S extends AbstractIoSession>
-
doDispose
protected abstract void doDispose() throws java.lang.ExceptionDispose the resources used by thisIoProcessorfor polling the client connections. The implementing class doDispose method will be called.- Throws:
java.lang.Exception- if some low level IO error occurs
-
select
protected abstract int select(long timeout) throws java.lang.Exceptionpoll those sessions for the given timeout- Parameters:
timeout- milliseconds before the call timeout if no event appear- Returns:
- The number of session ready for read or for write
- Throws:
java.lang.Exception- if some low level IO error occurs
-
select
protected abstract int select() throws java.lang.Exceptionpoll those sessions forever- Returns:
- The number of session ready for read or for write
- Throws:
java.lang.Exception- if some low level IO error occurs
-
isSelectorEmpty
protected abstract boolean isSelectorEmpty()
Say if the list ofIoSessionpolled by thisIoProcessoris empty- Returns:
trueif at least a session is managed by thisIoProcessor
-
wakeup
protected abstract void wakeup()
Interrupt theselect(long)call.
-
allSessionsCount
protected abstract int allSessionsCount()
Get the number ofIoSessionpolled by thisIoProcessor- Returns:
- the number of sessions attached to this
IoProcessor
-
selectedSessions
protected abstract java.util.Iterator<S> selectedSessions()
- Returns:
IteratorofIoSessionread for I/Os operation
-
getState
protected abstract SessionState getState(S session)
Get the state of a session (One of OPENING, OPEN, CLOSING)- Parameters:
session- theIoSessionto inspect- Returns:
- the state of the session
-
isWritable
protected abstract boolean isWritable(S session)
Tells if the session ready for writing- Parameters:
session- the queried session- Returns:
trueis ready,falseif not ready
-
isReadable
protected abstract boolean isReadable(S session)
Tells if the session ready for reading- Parameters:
session- the queried session- Returns:
trueis ready,falseif not ready
-
setInterestedInWrite
protected abstract void setInterestedInWrite(S session, boolean isInterested) throws java.lang.Exception
Set the session to be informed when a write event should be processed- Parameters:
session- the session for which we want to be interested in write eventsisInterested-truefor registering,falsefor removing- Throws:
java.lang.Exception- If there was a problem while registering the session
-
setInterestedInRead
protected abstract void setInterestedInRead(S session, boolean isInterested) throws java.lang.Exception
Set the session to be informed when a read event should be processed- Parameters:
session- the session for which we want to be interested in read eventsisInterested-truefor registering,falsefor removing- Throws:
java.lang.Exception- If there was a problem while registering the session
-
isInterestedInRead
protected abstract boolean isInterestedInRead(S session)
Tells if this session is registered for reading- Parameters:
session- the queried session- Returns:
trueis registered for reading
-
isInterestedInWrite
protected abstract boolean isInterestedInWrite(S session)
Tells if this session is registered for writing- Parameters:
session- the queried session- Returns:
trueis registered for writing
-
init
protected abstract void init(S session) throws java.lang.Exception
Initialize the polling of a session. Add it to the polling process.- Parameters:
session- theIoSessionto add to the polling- Throws:
java.lang.Exception- any exception thrown by the underlying system calls
-
destroy
protected abstract void destroy(S session) throws java.lang.Exception
Destroy the underlying client socket handle- Parameters:
session- theIoSession- Throws:
java.lang.Exception- any exception thrown by the underlying system calls
-
read
protected abstract int read(S session, IoBuffer buf) throws java.lang.Exception
Reads a sequence of bytes from aIoSessioninto the givenIoBuffer. Is called when the session was found ready for reading.- Parameters:
session- the session to readbuf- the buffer to fill- Returns:
- the number of bytes read
- Throws:
java.lang.Exception- any exception thrown by the underlying system calls
-
write
protected abstract int write(S session, IoBuffer buf, int length) throws java.io.IOException
Write a sequence of bytes to aIoSession, means to be called when a session was found ready for writing.- Parameters:
session- the session to writebuf- the buffer to writelength- the number of bytes to write can be superior to the number of bytes remaining in the buffer- Returns:
- the number of byte written
- Throws:
java.io.IOException- any exception thrown by the underlying system calls
-
transferFile
protected abstract int transferFile(S session, FileRegion region, int length) throws java.lang.Exception
Write a part of a file to aIoSession, if the underlying API isn't supporting system calls like sendfile(), you can throw aUnsupportedOperationExceptionso the file will be send using usualwrite(AbstractIoSession, IoBuffer, int)call.- Parameters:
session- the session to writeregion- the file region to writelength- the length of the portion to send- Returns:
- the number of written bytes
- Throws:
java.lang.Exception- any exception thrown by the underlying system calls
-
add
public final void add(S session)
Adds the specifiedsessionto the I/O processor so that the I/O processor starts to perform any I/O operations related with thesession.- Specified by:
addin interfaceIoProcessor<S extends AbstractIoSession>- Parameters:
session- The added session
-
remove
public final void remove(S session)
Removes and closes the specifiedsessionfrom the I/O processor so that the I/O processor closes the connection associated with thesessionand releases any other related resources.- Specified by:
removein interfaceIoProcessor<S extends AbstractIoSession>- Parameters:
session- The session to be removed
-
scheduleRemove
private void scheduleRemove(S session)
-
write
public void write(S session, WriteRequest writeRequest)
Writes the WriteRequest for the specifiedsession.- Specified by:
writein interfaceIoProcessor<S extends AbstractIoSession>- Parameters:
session- The session we want the message to be writtenwriteRequest- the WriteRequest to write
-
flush
public final void flush(S session)
Flushes the internal write request queue of the specifiedsession.- Specified by:
flushin interfaceIoProcessor<S extends AbstractIoSession>- Parameters:
session- The session we want the message to be written
-
updateTrafficMask
public final void updateTrafficMask(S session)
Updates the traffic mask for a given session- Parameters:
session- the session to update
-
startupProcessor
private void startupProcessor()
Starts the inner Processor, asking the executor to pick a thread in its pool. The Runnable will be renamed
-
registerNewSelector
protected abstract void registerNewSelector() throws java.io.IOExceptionIn the case we are using the java select() method, this method is used to trash the buggy selector and create a new one, registring all the sockets on it.- Throws:
java.io.IOException- If we got an exception
-
isBrokenConnection
protected abstract boolean isBrokenConnection() throws java.io.IOExceptionCheck that the select() has not exited immediately just because of a broken connection. In this case, this is a standard case, and we just have to loop.- Returns:
trueif a connection has been brutally closed.- Throws:
java.io.IOException- If we got an exception
-
read
private void read(S session)
-
updateTrafficControl
public void updateTrafficControl(S session)
Controls the traffic of the specifiedsessiondepending of theIoSession.isReadSuspended()andIoSession.isWriteSuspended()flags- Specified by:
updateTrafficControlin interfaceIoProcessor<S extends AbstractIoSession>- Parameters:
session- The session to be updated
-
-