asynchronous - Java Non-blocking IO CPU Leak -


i written simple nio server:

public static void main(string[] args) throws exception {     bytebuffer buffer = bytebuffer.allocatedirect(65536);     selector selector = selector.open();     serversocketchannel server = serversocketchannel.open();     server.configureblocking(false);     server.bind(new inetsocketaddress(724));     server.register(selector, selectionkey.op_accept);     while(server.isopen())     {         selector.selectnow();         iterator<selectionkey> iterator = selector.selectedkeys().iterator();         while(iterator.hasnext())         {             selectionkey key = iterator.next();             iterator.remove();             if(!key.isvalid())             {                 system.out.println("invalid key removed!");                 key.channel().close();                 key.cancel();                 continue;             }             if(key.isacceptable())             {                 server.accept().configureblocking(false).register(selector, selectionkey.op_read);                 system.out.println("accepting channel...");                 continue;             }             if(key.isreadable())             {                 socketchannel channel = (socketchannel) key.channel();                 try                 {                     channel.read((bytebuffer) buffer.clear());                     if(buffer.flip().limit() == 0)                     {                         continue;                     }                     system.out.println(buffer.get() & 0xff);                 } catch(exception e)                 {                     e.printstacktrace();                     channel.close();                     key.cancel();                 }             }         }     } } 

and it's client:

public static void main(string[] args) throws exception {     try(socket socket = new socket("localhost", 724))     {         outputstream output = socket.getoutputstream();         output.write(15);         output.flush();     } } 

once client disconnected server, load on cpu increases 40% enter image description here

i tried find solution, search has given nothing. think due fact selector not remove disconnect client, not know how test - whether client disconnected or not. channel.isopen() returns true.

from javadoc selector.selectnow()

this method performs non-blocking selection operation. if no channels have become selectable since previous selection operation method returns zero.

yes, that's going burn cpu; it's non-blocking , have tight loop.

edit add: idea behind using selector use blocking select() or select(long timeout) versions means socket something, unblocks.


Comments

Popular posts from this blog

basic authentication with http post params android -

vb.net - Virtual Keyboard commands -

css - Firefox for ubuntu renders wrong colors -