简体   繁体   中英

Is it possible to make blocking java socket read non active waiting?

I have an application that needs to have thousands of socket connections open and waiting for a message. The client is using java blocking socket read. That means that I will be able to have only N concurrent opened connection(based on the executor number of thread set) as all the N threads will be blocked on active wait (RUNNABLE state)

Is there a way to make those socket read to "wake up" the the thread when data is available (in the same fashion of NIO sockets)?

ie Current behaviour thread-pool (4 threads)

  • socketRead0(..) - RUNNABLE
  • socketRead0(..) - RUNNABLE
  • socketRead0(..) - RUNNABLE
  • socketRead0(..) - RUNNABLE

No more thread can execute

Desired Behaviour thread-pool (4 threads)

  • socketRead0(..) - WAITING (parking)
  • socketRead0(..) - WAITING (parking)
  • socketRead0(..) - WAITING (parking)
  • socketRead0(..) - WAITING (parking)
  • socketRead0(..) - RUNNABLE (it is executing read and will return data)

This way another thread having a socket read where data is available can kick in and get executed whilst others are waiting

NOTE: I know this can be achieved with NIO but want to know how can this behaviour be transferred to legacy sync calls (if possible) Thank you

The answer is NO. All method of java.net.SocketInputStream are blocking. InputStream.available() is not implemented and always return 0. Without NIO the only way is to use one thread per socket.

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