每个客户端一个线程.可行吗? [英] One thread per client. Doable?

查看:24
本文介绍了每个客户端一个线程.可行吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个 Java 服务器,它使用普通套接字来接受来自客户端的连接.我正在使用相当简单的模型,其中每个连接都有自己的线程在阻塞模式下从它读取.伪代码:

I'm writing a Java server which uses plain sockets to accept connections from clients. I'm using the fairly simple model where each connection has its own thread reading from it in blocking mode. Pseudo code:

handshake();

while(!closed) {
  length = readHeader(); // this usually blocks a few seconds
  readMessage(length);
}

cleanup();

(线程是从 Executors.newCachedThreadPool() 创建的,因此启动它们时不应该有任何显着的开销)

(Threads are created from an Executors.newCachedThreadPool() so there shouldn't be any significant overhead in starting them)

我知道这有点幼稚,如果线程是专用的操作系统线程,它就不能很好地扩展到许多连接.但是,我听说 Java 中的多个线程可以共享一个硬件线程.是真的吗?

I know this is a bit of a naive setup and it wouldn't really scale well to many connections if the threads were dedicated OS threads. However, I've heard that multiple threads in Java can share one hardware thread. Is that true?

知道我将在 Linux 上使用 Hotspot VM,在一台具有 8 核和 12GB RAM 的服务器上,您认为此设置适用于数千个连接吗?如果不是,有哪些替代方案?

Knowing that I'll be using the Hotspot VM on Linux, on a server with 8 cores and 12GB of RAM, do you think this setup will work well for thousands of connections? If not, what are the alternatives?

推荐答案

这可以很好地扩展到数百个连接,而不是数千个.一个问题是 Java 线程也需要相当多的堆栈(例如 256K),并且操作系统在调度所有线程时会遇到问题.

This will scale well for up to hundreds of connections, not to thousands. One issue is that a Java thread takes quite a bit of stack as well (e.g. 256K), and the OS will have problems scheduling all your threads.

看看 Java NIO 或框架,它们将帮助您更轻松地开始处理复杂的事情(例如 Apache Mina)

Look at Java NIO or framworks that will help you get started doing complex stuff more easily (e.g. Apache Mina)

这篇关于每个客户端一个线程.可行吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆