Apache mina-processor Threading Logic

Source: Internet
Author: User
Tags sessions


Processor is a private class inside a abstractpollingioprocessor abstract class.

The Processor is a primary loop body that handles I/O output data streams.

Processor's main work includes:


1, priority to deal with the new iosession logic processing

2. Jitter Processing

3, iosession input and output work.



The logic processing of the new iosession

Loop private final queue<s> newsessions = new concurrentlinkedqueue<s> (); Concurrent queues, which are processed if a new iosession is present

/**
* Loops over the new sessions blocking queue and returns the number of
* Sessions which is effectively created
*
* @return The number of new sessions
*/
private int handlenewsessions ()

{
int addedsessions = 0;
The acceptor thread puts the new link through the concurrent queue into the ioproccessor thread. Ioproccessor thread-first new linked socket
For (S session = Newsessions.poll (); session = NULL; session = Newsessions.poll ()) {
if (Addnow (session)) {
A New session has been created
addedsessions++;
}
}


return addedsessions;
}

The iosession associated with the channel is set to non-blocking mode. and register Selectionkey.op_read in selector.

protected void Init (Niosession session) throws Exception {
Selectablechannel ch = (Selectablechannel) session.getchannel ();
Ch.configureblocking (FALSE);
Session.setselectionkey (Ch.register (selector, selectionkey.op_read, session));
}

/**
* Process a new session:
*-Initialize it
*-Create its chain
*-Fire The CREATED listeners if any
*
* @param session the session to create
* @return True if the session has been registered
*/
Private Boolean Addnow (S session) {
Boolean registered = FALSE;
Process a new socket, initialize iosession, create a handler chain and create listeners
try {
Init (session);//Initialize Iosession
Registered = TRUE;

Establish iosession associated chain Filter to process the data logic
Build The filter chain of this session.
Iofilterchainbuilder ChainBuilder = Session.getservice (). Getfilterchainbuilder ();
Chainbuilder.buildfilterchain (Session.getfilterchain ());

Here we deal with events such as the creation of Iosession. This is a listening mode.
Defaultiofilterchain.connect_future is cleared inside here
In abstractiofilterchain.firesessionopened ().
Propagate the session_created event up to the chain
Ioservicelistenersupport listeners = ((Abstractioservice) Session.getservice ()). Getlisteners ();
Listeners.firesessioncreated (session);
} catch (Exception e) {
Exceptionmonitor.getinstance (). Exceptioncaught (e);


try {
Destroy (session);
} catch (Exception E1) {
Exceptionmonitor.getinstance (). Exceptioncaught (E1);
} finally {
Registered = FALSE;
}
}


return registered;
}

After the new iosession logic is processed, it is the main logical processing of the iosession. Includes read and write operations for data.

/**
* Deal with session ready for the read or write operations, or both.
*/
private void Process (S session)
{
Process Reads
The place to actually perform IO read and write operations
if (IsReadable (session) &&!session.isreadsuspended ())
{
Performing IO read operations
Read (session);
}


Process writes
if (iswritable (session) &&!session.iswritesuspended ())
{
Add the session to the queue, if it's not already there
if (Session.setscheduledforflush (true))
{
Flushingsessions.add (session);
}
}
}

The following is the main operation of Ioproccessor about reading data. In the read process, Apache Mina controls the next Iobuffer size based on the amount of data read per time.

In the I/O read process, because Java cannot directly process memory data. The container requires an internal heap memory request every time, which makes the pressure on the Java GC much larger. A iobuff is provided in Java NiO as a mapping of underlying memory.

Encapsulates the association for underlying memory. facilitates the provision of Java's ability to handle network input and output. In Ioprocessor, only the reading and writing of the data is processed, and the logic of the data is not processed. including subcontracting, package structure processing.

Where the IO read operation is actually performed in the Ioprocessor
private void Read (S session)
{//iosession is configured for data input and output. Including buffer size settings, etc.
Iosessionconfig config = Session.getconfig ();
The number of bytes that can be read in the socket
int buffersize = Config.getreadbuffersize ();
Iobuffer buf = iobuffer.allocate (buffersize);
Determine if a packet is subcontracting
Final Boolean hasfragmentation = Session.gettransportmetadata (). Hasfragmentation ();


try {
int readbytes = 0;
int ret;


try {
if (hasfragmentation) {


while (ret = read (session, BUF)) > 0) {
Readbytes + = ret;


if (!buf.hasremaining ()) {
Break
}
}
} else {
RET = Read (session, BUF);


if (Ret > 0) {
Readbytes = ret;
}
}
} finally {
Buf.flip ();
}


if (readbytes > 0)
{
The associated filter chain in the Filterchain associated with the session. The byte length is continuously read through the pre-set Iobuff size, which is then handed to filterchain for processing. Ioprocessor the logic of the data flow is not processed during the read process. Just read
Iofilterchain Filterchain = Session.getfilterchain ();
Filterchain.firemessagereceived (BUF);
BUF = null;
Automatically sets the size of the next buffer data if it is in a sub-package
if (hasfragmentation) {
if (readbytes << 1 < config.getreadbuffersize ()) {
Session.decreasereadbuffersize ();
} else if (readbytes = = Config.getreadbuffersize ()) {
Session.increasereadbuffersize ();
}
}
}


if (Ret < 0) {
Scheduleremove (session);
Iofilterchain Filterchain = Session.getfilterchain ();
Filterchain.fireinputclosed ();
}
} catch (Exception e) {
if (e instanceof IOException) {
if (! ( e instanceof portunreachableexception)
|| ! AbstractDatagramSessionConfig.class.isAssignableFrom (Config.getclass ())
|| ((abstractdatagramsessionconfig) config). iscloseonportunreachable ()) {
Scheduleremove (session);
}
}


Iofilterchain Filterchain = Session.getfilterchain ();
Filterchain.fireexceptioncaught (e);
}
}


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Apache mina-processor Threading Logic

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.