Jetlang NioFiber

70 views
Skip to first unread message

Mike Rettig

unread,
Jul 29, 2014, 12:23:27 PM7/29/14
to jetla...@googlegroups.com
http://code.google.com/p/jetlang/source/browse/trunk/src/test/java/org/jetlang/fibers/NioFiberTest.java
http://code.google.com/p/jetlang/source/browse/trunk/src/main/java/org/jetlang/fibers/NioFiberImpl.java

I committed a new nio based fiber implementation. It works like any other fiber and adds the ability to get callbacks on the fiber for nio asynchronous events.  The NioFiber makes it easy to manage application state and io data from a single thread.  This often results in better performance and more maintainable code.

Thanks in advance for any feedback.

Mike 


Example with Pipe:

@Test
    public void pipeData() throws IOException, InterruptedException {
        final CountDownLatch latch = new CountDownLatch(10);
        NioChannelHandler.PipeReader pipePing = new NioChannelHandler.PipeReader() {
            int count = 1;
            private ByteBuffer buffer = ByteBuffer.allocate(4);

            @Override
            protected void onData(Pipe.SourceChannel source) {
                try {
                    source.read(buffer);
                    if (buffer.position() == 4) {
                        buffer.flip();
                        assertEquals(count, buffer.getInt());
                        count++;
                        buffer.clear();
                        latch.countDown();
                    }
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        };
        NioFiber fiber = new NioFiberImpl();
        fiber.addHandler(pipePing);
        fiber.start();

        final Pipe.SinkChannel sink = pipePing.getSink();
        for (int i = 1; i < 11; i++) {
            ByteBuffer b = ByteBuffer.allocateDirect(4);
            b.putInt(i);
            b.flip();
            while (b.hasRemaining()) {
                sink.write(b);
            }
        }

        final boolean await = latch.await(10, TimeUnit.SECONDS);
        assertTrue(await);
        fiber.dispose();
    }
Reply all
Reply to author
Forward
0 new messages