如何选择Java Nio vs io? [英] how to choose java nio vs io?

查看:78
本文介绍了如何选择Java Nio vs io?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们知道,如果要使用传统的IO来构建服务器,则它必须在某个位置阻塞,因此我们不得不使用循环或一个线程的一种套接字模式,因此nio似乎是更好的选择.所以我想知道nio是否永远是更好的选择?

解决方案

恕我直言,阻塞IO通常是最简单的使用方法,除非您有特定的要求,而这又需要系统中的更多要求,否则您应该坚持使用最简单的方法. /p>

下一个最简单的选择是阻止NIO,如果我想获得比IO更高的效率或控制能力,我通常会首选它.它仍然相对简单,但是允许您使用ByteBuffers.例如ByteBuffer支持Little Endian.

一个常见的选择是将非阻塞NIO与选择器一起使用.这种引入的许多复杂性可以通过诸如Netty或Mina之类的框架来处理.如果您需要非阻塞IO,例如,我建议您使用这样的库.因为每个服务器有数千个并发连接.恕我直言,您有成千上万个连接,除非每个连接所做的工作都很琐碎,否则应该考虑拥有更多服务器. AFAIK google会使用更多服务器,而不是每台服务器数千名用户.

更极端的选择是使用NIO2.它比非阻塞NIO更加复杂和冗长.我不知道有什么框架可以很好地支持这一点.即实际上,这样做的速度更快. AFAIK如果您拥有Infiniband(这是设计要支持的功能),那么这似乎值得使用,但是如果您具有以太网,则可能不值得使用.

As we had known, If we want to use traditional IO to construct server, it must block somewhere, so we had to use loop or one thread one socket mode, So nio seem it is better choice. So I want know if the nio is better choice forever?

解决方案

IMHO, Blocking IO is generally the simplest to use, and unless you have a specific requirement which demands more from your system, you should stick with simplest option.

The next simplest option is blocking NIO, which I often prefer if I want something more efficiency or control than IO. It is still relatively simple but allows you to use ByteBuffers. e.g. ByteBuffers support little endian.

A common option is to use non-blocking NIO with Selectors. Much of the complexity this introduces can be handled by frameworks such as Netty or Mina. I suggest you use such a library if you need non-blocking IO e.g. because you have thousands of concurrent connections per server. IMHO You have thousands of connections, you should consider having more servers unless what each connection does is pretty trivial. AFAIK google go for more servers rather thousands of users per server.

The more extreme option is to use NIO2. This is even more complex and lengthy it write than non-blocking NIO. I don't know of any frameworks which support this well. i.e. it is actually faster when you do. AFAIK It appears this is worth using if you have Infiniband (which is what it was designed to support) but perhaps not worth using if you have Ethernet.

这篇关于如何选择Java Nio vs io?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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