简体   繁体   中英

Java NIO Http client requests with thread pools

Thread Pool Executor uses number of threads for Future Task. It assigns at least one thread until run() or call() returns.

So, I am confused on how to use Thread Pool for JAVA NIO HTTP requests.

1) Which thread will run the event loop

2) As threads won't block on IO, They will exit the run/call method. Then who takes care of invoking their handlers.

My Question is how to use Java NIO based HTTP POST client requests with thread pools ( Because of the High number of HTTP requests that we need to make), Or with Java NIO it is really not needed to run them on multiple threads, as the thread will never sleeps ( It always executes as there is nothing to block)

Okay, this is the philosophy. Multithreading can be used in 2 flavours (may be more, but it is not significant in this case). Traditional multithreading uses threads and blocking I/O. Task-grained multithreading (please suggest better term) is built upon traditional one and exploits following restrictions:

  • task of type Runnable is a unit of work;
  • task may not block;
  • if a task wants to wait for a long event (eg finish of I/O or time interval) it prepares another task and arranges it to run after the event, and exits (returns from Runnable.run() ).

Tasks are submitted for execution to a thread pool.

Asynchronous I/O perfectly fits in task-oriented model. Futures are glue between thread-oriented and task-oriented programming styles. They can be used to pass information from tasks to threads, but not in opposite direction, because tasks may not block. So you need not to use Futures at all when designing fully asynchronous server.

NIO1 requires a selector thread. Create and run it separately of the thread pool. NIO2 (java7) does not require selector thread (it maintains it in the background so that user does not to bother).

It is easy to find examples of NIO servers. df4j has examples of echo-servers (but not http servers) for both NIO1 and NIO2.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM