How to make a call with a delay of a non-blocking function

I want to call the add function for a HashSet with some delay, but not blocking the current thread. Is there a simple solution to achieve something like this:

 Utils.sleep(1000, myHashSet.add(foo)); //added after 1 second //code here runs immediately without delay ... 
+4
source share
3 answers

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 in a separate thread. However, be careful when modifying myHashSet at the same time. If you are simultaneously modifying a collection from another thread or trying to iterate over it, you may have problems and you will need to use locks.

+3
source

The usual vanilla solution would be:

  new Thread( new Runnable() { public void run() { try { Thread.sleep( 1000 ); } catch (InterruptedException ie) {} myHashSet.add( foo ); } } ).start(); 

There is much less going on behind the scenes here than with ThreadPoolExecutor. TPE may be more convenient to control the number of threads, but if you turn off a lot of threads that are sleeping or waiting, limiting their number can hurt performance a lot more than it helps.

And you want to sync with myHashSet if you haven't processed it yet. Remember that you need to sync everywhere so that it benefits. There are other ways to handle this, such as Collections.synchronizedMap or ConcurrentHashMap.

+9
source

Source: https://habr.com/ru/post/1415966/


All Articles