java - is it safe to store threads in a ConcurrentMap? -
i building backend service whereby rest call service creates new thread. thread waits rest call if not receive 5 minutes thread die. keep track of threads have collection keeps track of running threads when rest call comes in such user accepting or declining action, can identify thread using userid. if declined remove thread collection if accepted thread can carry on doing next action. have implemented using concurrentmap avoid concurrency issues.
since first time working threads want make sure not overlooking issues may arise. please have @ code , tell me if better or if there's flaws.
public class useraction extends thread { int userid; boolean isaccepted = false; boolean isdeclined = false; long timenow = system.currenttimemillis(); long timeelapsed = timenow + 50000; public useraction(int userid) { this.userid = userid; } public void declinejob() { this.isdeclined = true; } public void acceptjob() { this.isaccepted = true; } public boolean waitforapproval(){ while (system.currenttimemillis() < timeelapsed){ system.out.println("waiting approval"); if (isaccepted) { return true; } else if (declined) { return false; } } return isaccepted; } @override public void run() { if (!waitforapproval) { // mustve timed out or user declined remove list , return thread tcollection.remove(userid); // end thread here return; } // mustve been accepted continue working } } public class controller { public static concurrenthashmap<integer, thread> tcollection = new concurrenthashmap<>(); public static void main(string[] args) { int barberid1 = 1; int barberid2 = 2; tcollection.put(barberid1, new useraction(barberid1)); tcollection.put(barberid2, new useraction(barberid2)); tcollection.get(barberid1).start(); tcollection.get(barberid2).start(); thread.sleep(1000); // simulate rest call accepting/declining job after 1 second. in spring mvc restcontroller in different class. tcollection.get(barberid1).acceptjob(); tcollection.get(barberid2).declinejob(); } }
you don't need (explicit) threads this. shared pool of task objects created on first rest call.
when second rest call comes, have thread use (the 1 that's handling rest call). need retrieve task object according user id. need rid of expired tasks, can done example delayqueue
.
pseudocode:
public void rest1(user u) { usertask ut = new usertask(u); pool.put(u.getid(), ut); delaypool.put(ut); // assuming usertask implements delayed 5 minute delay } public void rest2(user u, action a) { usertask ut = pool.get(u.getid()); if(!a.isaccepted() || ut == null) pool.remove(u.getid()); else process(ut); // clean pool expired tasks, can done in beginning // of method, if want make sure expired actions aren't performed while((usertask u = delaypool.poll()) != null) pool.remove(u.getid()); }
Comments
Post a Comment