UNIX Socket FAQ

A forum for questions and answers about network programming on Linux and all other Unix-like systems

You are not logged in.

  • Index
  • » Threads
  • » Realtime equivalent to Java's Thread.sleep()?

#1 2008-09-16 01:36 AM

PeterSteele
Member
Registered: 2008-01-26
Posts: 7

Re: Realtime equivalent to Java's Thread.sleep()?

I have an application that I want to guarantee that when I call Java's Thread.sleep(n) the thread will sleep for precisely that amount of time, or close to it at least. What we recently encountered though was that if the "wall clock" time is changed in one thread while a sleep is occurring in another thread, this clock change will impact when the sleeping thread will wake up.

In our case, we had a simple Thread.sleep(1000), and during that one second period another thread set the clock back two minutes. The sleeping thread ended up sleeping roughly two minutes and a second instead of just a second. Apparently this is a "feature" of Thread.sleep(), and I can see in some cases (e.g. a task scheduler based on wall clock times) where this is exactly the behavior you'd want. However, in our case, we want the sleep function to sleep by the amount we specify, regardless of changes to the wall clock time. Is there a way to do this in Java?

Offline

#2 2008-09-16 04:38 AM

PeterSteele
Member
Registered: 2008-01-26
Posts: 7

Re: Realtime equivalent to Java's Thread.sleep()?

I should note that our development platform is FreeBSD 7.0 with JDK 1.5.

Offline

#3 2008-09-16 07:53 AM

i3839
Oddministrator
From: Amsterdam
Registered: 2003-06-07
Posts: 2,239

Re: Realtime equivalent to Java's Thread.sleep()?

Try using nanosleep instead of sleep. No idea if that's easily done with Java, Java's
sleep function should use nanosleep already actually. If it does and the timewarp
stufff still happens then it's a FreeBSD bug.

Offline

#4 2008-09-16 05:33 PM

PeterSteele
Member
Registered: 2008-01-26
Posts: 7

Re: Realtime equivalent to Java's Thread.sleep()?

I wrote a jni wrapper to call the C nanosleep function. It seems to work as we need. Thanks for the pointer.

Offline

  • Index
  • » Threads
  • » Realtime equivalent to Java's Thread.sleep()?

Board footer

Powered by FluxBB