views:

44

answers:

2

I have a program whose only purpose is to drive a java.awt.Robot in an infinite loop until an exit condition is met.

The robot performs a number of actions in quick succession, which require a standard UI delay between them. For this, I use java.awt.Robot.setAutoDelay(int ms), which appears to be designed for precisely this purpose.

At other times, however, I need to insert arbitrarily long delays for operations to complete. I appear to have a choice between using java.awt.Robot.delay(int ms) or java.lang.Thread.sleep(long ms), and am curious what the differences between them are, and which I should use.

My gut instinct was to keep all my operations in the same "place", and use java.awt.Robot.delay(int ms). However, after thinking about it for a moment, I assumed that java.awt.Robot.delay(int ms) would put an operation on the Robot's stack of operations to complete, and if those were my only delays in an infinite loop, I may very quickly, and needlessly, generate an absurdly large queue of events for the Robot.

At that point, I checked the API for java.awt.Robot.delay(int ms), which told me the following:

Sleeps for the specified time. To catch any InterruptedExceptions that occur, Thread.sleep() may be used instead.

Having failed to gain any useful insight into the matter, I elected to ask you guys.

+1  A: 

At first I would also assume that using delay() would generate a large queue of events, in particular after reading the javadoc for waitForIdle():

Waits until all events currently on the event queue have been processed

but checking the source code of Robot.delay() shows that it basically is a Thread.sleep(), after checking that the delay time is positive and not more than 1 minute!

Abstract: both solutions are almost the same, use Thread.sleep() for delaying longer than 1 minute or catching the InterruptedException.

after years of programming with Java I found how to sleep without having to catch the InterruptedException (disregarding the overhead of creating a Robot)

Carlos Heuberger
+1  A: 

However, after thinking about it for a moment, I assumed that java.awt.Robot.delay(int ms) would put an operation on the Robot's stack of operations to complete, and if those were my only delays in an infinite loop, I may very quickly, and needlessly, generate an absurdly large queue of events for the Robot.

Your fears are unfounded. The delay(int) method does exactly what the javadoc says it does. It delays the calling thread rather than inserting a "delay for so long" event onto the Robot instance's queue.

Stephen C