java - Avoiding a possible concurrency issue with a LIST being returned -
here sequence bother me begging standard remedy concurrency issue
- create list object (lst)
- initiate multple threads (updater threads)
- send lst each updater threads update (add) it.
- wait defined time (t1) let updater threads proceed updates.
- after t1 time expired, return lst application (consumer-app) isn't in our control.
- when return it, updater threads may still updating lst.
- consumer-app doesn't know whether list still being updating in background updater threads.
- consumer-app list operations (add/remove) on lst.
problem : lead concurrency issue.
how tackle this?
how stop updating threads after t1 effectively? or there standard way deal on this? synchronizedlist (collections.synchronizedlist(new arraylist())) in this?
edit : i'm aware of copyonwritearraylist also. i'm focusing on simple arraylist on this
you use executor service create , terminate threads, along copyonwritearraylist address concurrency.
private copyonwritearraylist<someobject> somearraylist = new copyonwritearraylist<someobject>(); ...
class nodestatusthread implements runnable { private executorservice updaterthreadexecutor = null; private int numthrd = 20; //threads private int timeout = 10; // ten-seconds @override public void run() { (int i=0;i<numthrd; i++ ) { updaterthreadexecutor.execute(new updaterthread()); } updaterthreadexecutor.shutdown(); try{ //wait thread completion if(!updaterthreadexecutor.awaittermination(timeout, timeunit.seconds)){ //return false timeout surpassed updaterthreadexecutor.shutdownnow(); //forces thread termination } }catch(interruptedexception e){ updaterthreadexecutor.shutdownnow(); } } } ...
class updaterthread implements runnable { @override public void run() { omearraylist.add(someobject); somearraylist.remove(someobject); } }
Comments
Post a Comment