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

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

问题描述

我正在编写一个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)

我知道这是一个天真的设置,它不会很好地扩展到如果线程是专用的OS线程,那么很多连接。但是,我听说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或者framworks将帮助您更容易地开始复杂的事情(例如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天全站免登陆