Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a delayed non-blocking function call

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
...
like image 483
Thomas Avatar asked Jun 04 '12 14:06

Thomas


1 Answers

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.

like image 143
RalphChapin Avatar answered Sep 19 '22 00:09

RalphChapin