本文介绍了2011年的Java:线程套接字VS NIO:在64位操作系统和最新的Java版本上可以选择什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在StackOverflow和一些博客上阅读了几篇关于java.net vs java.nio的帖子。但我仍然无法理解何时应该更喜欢NIO而不是螺纹插座。你能否检查我下面的结论并告诉我哪些不正确以及哪些错过了?

I've read several posts about java.net vs java.nio here on StackOverflow and on some blogs. But I still cannot catch an idea of when should one prefer NIO over threaded sockets. Can you please examine my conclusions below and tell me which ones are incorrect and which ones are missed?


  • 因为在线程模型中你需要为每个活动连接专用一个线程,并且每个线程为其堆栈提供大约250千字节的内存,使用每个套接字的模型,您将在大量并发连接上快速耗尽内存。与NIO不同。

  • Since in threaded model you need to dedicate a thread to each active connection and each thread takes like 250Kilobytes of memory for it's stack, with thread per socket model you will quickly run out of memory on large number of concurrent connections. Unlike NIO.

在现代操作系统和处理器中,大量活动线程和上下文切换时间对性能几乎无关紧要

In modern operating systems and processors a large number of active threads and context switch time can be considered almost insignificant for performance

NIO的整个吞吐量可能更低,因为异步NIO库在高负载环境中使用的select()和poll()比唤醒和放入休眠线程更昂贵。

NIO throughoutput can be lower because select() and poll() used by asynchronous NIO libraries in high-load environments is more expensive than waking up and putting to sleep threads.

NIO一直比较慢,但它允许您处理更多的并发连接。它本质上是一个时间/空间权衡:传统IO速度更快但内存占用更大,NIO速度更慢但使用的资源更少。

NIO has always been slower but it allows you to process more concurrent connections. It's essentially a time/space trade-off: traditional IO is faster but has a heavier memory footprint, NIO is slower but uses less resources.

Java有一个每个并发线程的硬限制为15000/30000,具体取决于JVM,这会将每个连接模型的线程限制为最大并发连接数,但JVM7将没有此限制(无法确认此数据)。

Java has a hard limit per concurrent threads of 15000 / 30000 depending on JVM and this will limit thread per connection model to this number of concurrent connections maximum, but JVM7 will have no such limit (cannot confirm this data).

所以,作为结论,你可以这样:

So, as a conclusion, you can have this:


  • 如果你有数万个并发连接 - 除非请求处理速度是你的关键因素,否则NIO是更好的选择

  • 如果你的连接数少于此数 - 每个连接的线程是一个更好的选择(假设您可以承受大量的RAM来保持所有并发线程的堆栈达到最大值)

  • 使用Java 7,您可能希望在任何一种情况下都使用NIO 2.0。

我是否正确?

推荐答案

那看对我来说是正确的,除了关于Java限制线程数量的部分 - 这通常受到运行的操作系统的限制(参见和)。

That seems right to me, except for the part about Java limiting the number of threads – that is typically limited by the OS it's running on (see How many threads can a Java VM support? and Can't get past 2542 Threads in Java on 4GB iMac OSX 10.6.3 Snow Leopard (32bit)).

要达到那么多线程,你可能需要调整JVM的堆栈大小。

To reach that many threads you'll probably need to adjust the stack size of the JVM.

这篇关于2011年的Java:线程套接字VS NIO:在64位操作系统和最新的Java版本上可以选择什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-31 12:53