Can you control the latency for java threads?
I'm creating a tiny server that will always listen for new connections. About 30 times a second the server will "wake up" and send an update request to a client. The client will be开发者_C百科 asleep until it's time to wake up (as established by the last connection) and accept the request and fire off the update. Because the window for the exchange is going to consistently be small, how do I manage the latency of the sleep thread to get a more accurate and precise measurement of sleep cycles?
No you can't.
What you have here is 2 absolutely different activities coupled together. One is responsible for periodical wakeups and the other takes care of updating the client. If the wakeup task waits for update task to be done then its accuracy will suffer.
What you can do is solve the problem by introducing some degree of asynchrony into your server.
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
final Runnable notificationTask = new Runnable() {
@Override public void run() {
updater.sendUpdate(); // just *notify* the updater to do an update
}
};
executor.scheduleAtFixedRate(
notificationTask, 0, 33333333, TimeUnit.NANOSECONDS // freakishly accurate :)
);
Why can't it stay awake throughout? Does the Observer / Observable pattern help you in any way?
精彩评论