java - How to make a delayed non-blocking function call -


i want call add function of hashset delay, without blocking current thread. there easy solution achieve this:

utils.sleep(1000, myhashset.add(foo)); //added after 1 second //code here runs without delay ... 

you can use scheduledthreadpoolexecutor.schedule:

scheduledthreadpoolexecutor exec = new scheduledthreadpoolexecutor(1);  exec.schedule(new runnable() {           public void run() {               myhashset.add(foo);           }      }, 1, timeunit.seconds); 

it execute code after 1 second on separate thread. careful concurrent modifications of myhashset though. if modifying collection @ same time different thread or trying iterate on may in trouble , need use locks.


Comments

Popular posts from this blog

jquery - Invalid Assignment Left-Hand Side -

javascript - Preserving URL fragment through CAS sign-on -

asp.net mvc - Implementing normal user/pass, Twitter & Facebook auth -