executorservice - How is an executor terminated in my Java program? -
this question related previous question : why speed of java process inside multiple loops slows down goes?
in order find problem of question, looked closely @ code , found executors in app not terminated, since i'm in process of learning how use executors, copied online sample codes , used them in app, , i'm not sure if i'm using them correctly.
what's difference between following 2 approaches of using executors ?
[1]
executor executor=executors.newfixedthreadpool(30); countdownlatch donesignal=new countdownlatch(280); (int n=0;n<280;n++) { ... executor.execute(new samplecountrunner(donesignal,...)); } try { donesignal.await(); } catch (exception e) { e.printstacktrace(); }
[2]
executorservice executor=executors.newfixedthreadpool(30); (int i=0;i<60;i++) { ... executor.execute(new xyzrunner(...)); } executor.shutdown(); while (!executor.isterminated()) { }
it seems me after 1st 1 done, executor still has active pool of threads running , waiting more tasks, consume cpu time , memory.
the 2nd 1 terminate active threads in pool after shutdown() method run, , active threads won't take more cpu time or memory after point.
so questions :
[1] correct ?
[2] how terminate pool of threads in 1st case ? there no "executor.shutdown()" executor
edit :
problem solved, changed executor in [1] executorservice, , added :
executor.shutdown(); while (!executor.isterminated()) { }
now when program ends, won't have lot of threads active more.
it seems me after 1st 1 done, executor still has active pool of threads running , waiting more tasks, consume cpu time , memory.
not exactly. in first approach , after tasks done ( signalled latch ) , executor not shutdown - threads in executor not consume cpu ( consume minimum memory needed thier structures yes ).
in approach - explicitly in control of knowing when , how tasks completed. can know if tasks have succeeded or failed , , can decide resubmit tasks if needed.
the 2nd 1 terminate active threads in pool after shutdown() method run, , active threads won't take more cpu time or memory after point.
again ,not .in approach , executorservice not shutdown after call shutdown()
. waits submitted tasks complete , here not directly know if these tasks completed or failed ( throwing exception
).
and until submitted tasks completed - isshutdown()
tight loop ( spike cpu near 100% ) .
Comments
Post a Comment