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) ?
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.