Mina2 thread details

Source: Internet
Author: User

1. Main Process


Read in data:
IoProcessor --- logging, decoding, threadPool (IoFilter) --- IoHandler)
Write out data:
Business logic processing (IoHandler) --- logging, encoding, threadPool (IoFilter) --- IO writing (IoProcessor)
From the above we can see that the process of IO reading and writing is the opposite.

2 threads
Here we mainly discuss the threads in Mina. Using threads and thread pools can improve performance. Mina uses several threads:

  • IoAcceptor/IoConnector thread
  • IoProcessor thread
  • IoHandler thread



2.1 IoAcceptor/IoConnector thread
IoAcceptor is used to listen to client connections. Every time a port is listened to, a thread is established. IoConnector is used to establish a connection with the server. Every time a server is connected, a thread is established. These two threads are created through the thread pool. We can specify the thread pool type when constructing the object:

 

 

[Java]
 
  1. Public NioSocketAcceptor (Executor executor, IoProcessor <NioSession> processor ){}
  2. Public NioSocketConnector (Executor executor, IoProcessor <NioSession> processor ){}


The construction of such thread pool is in the source code (rows actioservice 168th ):

 

 

[Java]
 
  1. Protected extends actioservice (IoSessionConfig sessionConfig, Executor executor ){
  2. // Omit Part of the Code
  3. If (executor = null ){
  4. This.exe cutor = Executors. newCachedThreadPool ();
  5. CreatedExecutor = true;
  6. } Else {
  7. This.exe cutor = executor;
  8. CreatedExecutor = false;
  9. }
  10. }


It can be seen that the default thread pool type is newCachedThreadPool, which is a thread pool for creating new threads as needed and can be reused when previously constructed threads are available.

2.2IoProcessor thread
For an IoAcceptor or IoConnector thread corresponding to an IoProcessor thread for IO processing, this IoProcessor thread is taken from the IoProcessor thread pool. The IoProcessor thread pool size defaults to the number of CPU cores of the machine + 1. For example, the IoProcessor thread pool size of the dual-core machine is 3 by default. We can change the thread pool size:

 

 

[Java]
 
  1. IoConnector conne= new NioSocketConnector (9 );
  2. IoAcceptor acceptor = new NioSocketAcceptor (9 );


As shown above, the IoProcessor thread pool size is changed to 9.
The default size of IoProcessor thread pool is defined in the source code (SimpleIoProcessorPool 82nd rows ):

 

Java code
  1. Private static final int DEFAULT_SIZE = Runtime. getRuntime (). availableProcessors () + 1;


The IoProcessor thread pool is constructed in the source code (SimpleIoProcessorPool row 144th ):

Java code
  1. Public SimpleIoProcessorPool (Class <? Extends IoProcessor <S> processorType,
  2. Executor executor, int size ){
  3. // Omit Part of the Code
  4. If (createdExecutor ){
  5. This.exe cutor = Executors. newCachedThreadPool ();
  6. } Else {
  7. This.exe cutor = executor;
  8. }
  9. }



2.3IoHandler thread
When the "threadPool" filter is not added to the filter chain, the business logic processing and IoProcessor use the same thread. If the "threadPool" filter is set, use the set thread pool to generate threads for business logic processing. The configuration of the filter is as follows:

Java code
  1. Acceptor. getFilterChain (). addLast ("threadPool", new ExecutorFilter (Executors. newCachedThreadPool ()));


After the above configuration, IO processing and business logic processing will use their respective thread pools to generate thread usage. If your application processes requests for a long time and wants the application to be responsive, it is best to put the tasks that process the business logic in a new thread for execution, instead of executing it in the thread created by the mina framework.

2.4 generation of various threads

  • When an IoAcceptor/IoConnector instance is created, an IoProcessor thread pool associated with IoAcceptor/IoConnector is also created.
  • When IoAcceptor/IoConnector establishes a socket (the bind () of IoAcceptor or the connect () method of IoConnector is called), It extracts a thread from the thread pool and listens to the socket port.
  • When IoAcceptor/IoConnector detects a connection request on the socket, an IoSession object is created and an IoProcessor thread is retrieved from the IoProcessor pool for IO processing.
  • If the "threadPool" filter is configured in the filter, the thread pool is used to establish the thread to execute the business logic (IoHandler) processing; otherwise, the IoProcessor thread is used to process the business logic.



3. View threads
For example, you can use the jdk built-in tool jvisualvm to view the thread:

Java code
  1. Public class MinaTest {
  2. Protected static Logger logger = LoggerFactory. getLogger (MinaTest. class );
  3. Private static int PORT = 9999;
  4. Public static void main (String [] args ){
  5. Try {
  6. // Create a non-blocking server Socket
  7. IoAcceptor acceptor = new NioSocketAcceptor ();
  8. // Set the filter
  9. Acceptor. getFilterChain (). addLast ("logger", new LoggingFilter ());
  10. Acceptor. getFilterChain (). addLast ("codec ",
  11. New ProtocolCodecFilter (new TextLineCodecFactory (Charset. forName ("UTF-8 "))));
  12. Acceptor. getFilterChain (). addLast ("threadPool", new ExecutorFilter (Executors. newCachedThreadPool ()));
  13. // Set the buffer size for reading data
  14. Acceptor. getSessionConfig (). setReadBufferSize (2048 );
  15. // No operation enters idle status within 10 seconds of the read/write Channel
  16. Acceptor. getSessionConfig (). setIdleTime (IdleStatus. BOTH_IDLE, 10 );
  17. // Bind a logical processor
  18. Acceptor. setHandler (new MinaServerHandler ());
  19. // Bind the port
  20. Acceptor. bind (new InetSocketAddress (PORT ));
  21. Logger.info ("server started successfully... the PORT number is:" + PORT );
  22. } Catch (Exception e ){
  23. Logger. error ("server startup exception...", e );
  24. E. printStackTrace ();
  25. }
  26. }
  27. }



Java code
  1. Public class MinaServerHandler extends IoHandlerAdapter {
  2. Protected static Logger logger = LoggerFactory. getLogger (MinaServerHandler. class );
  3. Public void exceptionCaught (IoSession session, Throwable cause) throws Exception {
  4. Logger. error ("the server sends an exception...", cause );
  5. }
  6. Public void messageReceived (IoSession session, Object message) throws Exception {
  7. String msg = message. toString ();
  8. // If quit is used, close the session and exit.
  9. If ("quit". equals (msg )){
  10. Session. close ();
  11. }
  12. Date date = new Date ();
  13. Session. write (date. toString ());
  14. }
  15. Public void sessionCreated (IoSession session) throws Exception {
  16. Logger.info ("create a connection between the server and the client ...");
  17. }
  18. }

 

  • Run the MinaTest class to start the server.
  • Start> RUN> cmd to enter the console window.
  • Input: telnet 127.0.0.1 9999.
  • Repeat steps 2 and 3 twice.
  • The thread view of jvisualvm is as follows:

 

 

    • Through the above steps, we can see that we opened a server port and connected with three clients. Next we will analyze the threads produced by the server through the above summary:
    • NioSccketAcceptor is a thread created through the thread pool for the server listening port 9999.
    • The NioProcessor-1, NioProcessor-2, and NioProcessor-3 are the threads created for the IoProcessor thread pool for IO processing.
    • Pool-3-thread-1, pool-3-thread-2, pool-3-thread-3 are the threads created for the thread pool configured by the filter for business logic processing.

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.