Reputation: 10669
I want to call the add
function of an HashSet with some delay, but without blocking the current thread. Is there an easy solution to achieve something like this:
Utils.sleep(1000, myHashSet.add(foo)); //added after 1 second
//code here runs immediately without delay
...
Upvotes: 13
Views: 24359
Reputation: 3158
The plain vanilla solution would be:
new Thread( new Runnable() {
public void run() {
try { Thread.sleep( 1000 ); }
catch (InterruptedException ie) {}
myHashSet.add( foo );
}
} ).start();
There's a lot less going on behind the scenes here than with ThreadPoolExecutor. TPE can be handy to keep the number of threads under control, but if you're spinning off a lot of threads that sleep or wait, limiting their number may hurt performance a lot more than it helps.
And you want to synchronize on myHashSet
if you haven't handled this already. Remember that you have to synchronize everywhere for this to do any good. There are other ways to handle this, like Collections.synchronizedMap or ConcurrentHashMap.
Upvotes: 13
Reputation: 62439
You can use ScheduledThreadPoolExecutor.schedule:
ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(1);
exec.schedule(new Runnable() {
public void run() {
myHashSet.add(foo);
}
}, 1, TimeUnit.SECONDS);
It will execute your code after 1 second on a separate thread. Be careful about concurrent modifications of myHashSet
though. If you are modifying the collection at the same time from a different thread or trying to iterate over it you may be in trouble and will need to use locks.
Upvotes: 16