0

I'm doing a sort of event loop to process multiple non-blocking sockets in Java. The problem is that when I leave the loop untouched, it uses a whole core. (For instance, I have a quad core and everytime I start my program, the CPU jumps to 25% everytime.)

I know I could use Thread.sleep() to slow down the usage of processor but I was wondering if there's a proper way of doing that. I feel like Thread.sleep(1) might be limitating my event loop.

So my question is, how should I do it? Is there a proper way of doing that? Should I reduce the thread's priority? Should I use Thread.sleep(0, someNanosecondsAmount) ?

SBSTP
  • 3,479
  • 6
  • 30
  • 41
  • I have tried Thread.yield(); does not work. Also netbeans says that yield might cause issues with synchronization which I am using. – SBSTP Jan 08 '13 at 14:57
  • 3
    Most people who use non-blocking IO use the `select()` method to wait for content. If you're not, perhaps you should. Or you should show us your code and indicate why you can't. – parsifal Jan 08 '13 at 14:58
  • 1
    However, unless you're expecting thousands of simultaneously-connected sockets, traditional blocking IO with multiple threads is almost certainly sufficient, and definitely easier to implement. – parsifal Jan 08 '13 at 15:00
  • What exactly do you mean with "process"? – Fildor Jan 08 '13 at 15:02
  • I have an ArrayList of ServerSocketChannels which are in non-blocking mode. I have a thread which goes though that list and calls the .accept() method on those channels. If it doesn't return null, it will fire an event though an interface passed to the class. I am trying to build a sort of Selector of my own – SBSTP Jan 08 '13 at 15:05
  • 1
    Don't reinvent the wheel. – parsifal Jan 08 '13 at 15:15
  • Why are the ServerSocketChannels non-blocking? What would happen if they didn't accept a connection for 1 to 10 ms? – Peter Lawrey Jan 08 '13 at 15:21

1 Answers1

2

All the sleep methods will sleep for a minimum on 1 ms. You can use yield() which is shorter but usually doesn't give up the CPU.

If you are busy waiting on a group of sockets, you will end up using a whole cpu or you will having milli-second latencies.

A better solution many be to use a Selector to wait until a Socket is ready to use or blocking NIO with a thread per connection.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • Well what I'm actually trying to do is a sort of selector. My goal was to be able to handle many channels using only 1 thread and a "processing loop" which fires events. Also, one of the reasons is because I don't like how Selectors work in Java. – SBSTP Jan 08 '13 at 17:52
  • AFAIK Your options are; use a Selector, periodic polling or busy waiting. I don't like Selector either, so I use either blocking NIO or busy waiting. – Peter Lawrey Jan 08 '13 at 17:55