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
...
You can use ScheduledThreadPoolExecutor.schedule:
It will execute your code after 1 second on a separate thread. Be careful about concurrent modifications of
myHashSetthough. 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.