Search code examples
javascalaasynchronousplayframeworknio

Scala play framework and NIO.2


I'm programming in scala to develop a web application using play framework 2.5.3, and I need to create a TCP server/client which will take advantage of play's asynchronous model. After a bit of reading. I learned about NIO.2's AsynchronousServerSocketChannel/AsynchronousSocketChannel in Java 7. I found an implementation of NIO.2 for Scala on Github here (https://gist.github.com/happy4crazy/1901b1be0cb924898d13).

After modifying it, I was able to run the code and examine the threads in jvisualvm. I noticed NIO.2 is creating it's own Thread's when accepting connections. I'm worried that NIO.2's Threads and play framework's dispatcher threads will cause problems and slow the web application when under high stress. Can this lead to problems, and is there a better way to integrate NIO.2 with play framework's asynchronous model?

Thanking you in advance Francis


Solution

  • When Play uses Netty for I/O, Netty has its own thread pool and it does not cause problems (https://www.playframework.com/documentation/2.5.x/ThreadPools). So I can suppose the fact NIO.2 has its own thread pool is safe either.

    Meanwhile, you can configure NIO.2 to use the same thread pool as Play. First, extract the Play's thread pool. Let it is named executor. Then

    AsynchronousChannelGroup group = AsynchronousChannelGroup.withThreadPool(executor);
    AsynchronousServerSocketChannel channel = AsynchronousServerSocketChannel.open(group);
    AsynchronousSocketChannel channel = AsynchronousSocketChannel.open(group);