How to make a delayed non-blocking function call

别来无恙 提交于 2019-12-01 05:50:12

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.

RalphChapin

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!