简体   繁体   English

是否可以使阻塞 java 套接字读取非活动等待?

[英]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.客户端正在使用 java 阻塞套接字读取。 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)这意味着我将只能有 N 个并发打开的连接(基于线程集的执行程序数),因为所有 N 个线程都将在活动等待时被阻塞(RUNNABLE 状态)

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)?有没有办法让这些套接字读取以在数据可用时“唤醒”线程(以与 NIO 套接字相同的方式)?

ie Current behaviour thread-pool (4 threads)即当前行为线程池(4个线程)

  • socketRead0(..) - RUNNABLE socketRead0(..) - 可运行
  • socketRead0(..) - RUNNABLE socketRead0(..) - 可运行
  • socketRead0(..) - RUNNABLE socketRead0(..) - 可运行
  • socketRead0(..) - RUNNABLE socketRead0(..) - 可运行

No more thread can execute没有更多的线程可以执行

Desired Behaviour thread-pool (4 threads)期望行为线程池(4 个线程)

  • socketRead0(..) - WAITING (parking) socketRead0(..) - 等待(停车)
  • socketRead0(..) - WAITING (parking) socketRead0(..) - 等待(停车)
  • socketRead0(..) - WAITING (parking) socketRead0(..) - 等待(停车)
  • socketRead0(..) - WAITING (parking) socketRead0(..) - 等待(停车)
  • socketRead0(..) - RUNNABLE (it is executing read and will return data) socketRead0(..) - RUNNABLE(它正在执行读取并将返回数据)

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注意:我知道这可以通过 NIO 实现,但想知道如何将这种行为转移到旧版同步调用(如果可能)谢谢

The answer is NO.答案是不。 All method of java.net.SocketInputStream are blocking. java.net.SocketInputStream 的所有方法都是阻塞的。 InputStream.available() is not implemented and always return 0. Without NIO the only way is to use one thread per socket. InputStream.available() 没有实现并且总是返回 0。没有 NIO,唯一的方法是每个套接字使用一个线程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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