How to suspend a java thread for a small period of time, like 100 nanoseconds?

Viewed 38234

I know Thread.sleep() can make a java thread suspend for a while, like certain milliseconds and certain nanoseconds. But the problem is the invocation of this function also causes overhead.

For example, if I want a thread to suspend for 100 nanoseconds, and I call Thread.sleep(0, 100). The whole cost for this process is invocation_cost + 100 nanosceonds, which may be much larger the what I want. How could I avoid this problem, and achieve my purpose?

The reason I need this is that I want to do simulation offline. I profiled the execution time of a task; Now I want to simulate this execution time by suspending a thread in the same time period.

Thanks!

7 Answers

For waiting for an answer of a UDP request I wanted to use Threads.leep(millis, nanos) like sleep(0,10). When debugging into java source of sleep(...) I saw that nanos is ignored in windows java. If nanos > 0, millis will be incremented and then sleep(millis) will be called! In windows sleep 1 ms is the shortest way to sleep.

Suppose a producer thread is filling a work buffer, say a linked list. The buffer can be sized so it does not empty in less than a sleep-wake period, and the cpu can support the consumer threads that empty the buffer while you sleep. You might even up the buffer size until it is not empty when you wake. Now, how much sleep is a business decision, as there is switching overhead. Lots of hints on figuring that in the above!

Of course, there are several Blocking Concurrent Classes but generally their capacity is fixed. Blocking is no less expensive a thread suspend, I have to believe.

Related