【发布时间】:2017-03-04 23:46:18
【问题描述】:
import java.nio.channels.{AsynchronousServerSocketChannel, AsynchronousSocketChannel}
import java.net.InetSocketAddress
import scala.concurrent.{Future, blocking}
class Master {
val server: AsynchronousServerSocketChannel = AsynchronousServerSocketChannel.open()
server.bind(new InetSocketAddress("localhost", port))
val client: Future[AsynchronousSocketChannel] = Future { blocking { server.accept().get() } }
}
这是我正在尝试的伪代码。
在问这个问题之前,我搜索了一下,发现了一个相关的answer。
在她的回答中,我想知道这是什么意思:"If you want to absolutely prevent additional threads from ever being created, then you ought to use an AsyncIO library, such as Java's NIO library."
由于我不想遭受running out of memory(使用blocking时的情况)或thread pool hell(相反情况)的困扰,所以她的回答正是我一直期待的。但是,正如您在我的伪代码中看到的那样,由于blocking,将为每个客户端创建一个新线程(为了简单起见,我只创建了一个客户端),即使我按照她说的那样使用 NIO。
- 请用一个简单的例子解释她的建议。
- 在 Scala 中尝试异步 io 时,我的伪代码是一种合适的方法还是有更好的替代方法?
【问题讨论】: