Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
333 views
in Technique[技术] by (71.8m points)

multithreading - 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)?

i.e. 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

question from:https://stackoverflow.com/questions/65883402/is-it-possible-to-make-blocking-java-socket-read-non-active-waiting

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...