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
...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With