java - Running many thread and Stop thread on Exception -
i have thread (implements runnable) many branch officer call thread branch code. set name of thread branch code. problems are...
- when exception occurred in running thread - can't stop that. , when try make thread name "exceptionininitializererror" or "outofmemoryerror: java heap space" comes
- "outofmemoryerror: java heap space" exception comes when 2 or more thread running @ time.
public myrunnerclass { //this method called many branch branch code public void executebranchprocess(string branchcode){ thread t = new thread(new exporter(branchcode); t.setname(branchcode); t.start(); } }
thread class here
public class exporter implements runnable{ private string branchcode; public exporter(string branchcode){ this.branchcode = branchcode; } @override public void run() { try { exportcorner(); } catch (interruptedexception e) { e.printstacktrace(); } } private void exportcorner() throws interruptedexception{ try{ //some process }catch(exception e){ // want close running thread here // using closethread(this.branchcode), not working } } static void closethread(string branchcode) throws interruptedexception { thread thread = null; (thread t : thread.getallstacktraces().keyset()) { if (t.getname().equals(branchcode)) thread = t; } if (thread != null) { thread.interrupt(); thread.join(); } } }
you face multiple problems here:
you cannot join thread in itself. thread.join() waits until thread dies. if call thread want stop, waits forever.
to stop thread have return
run()
method. in case, addreturn
in catch clause instead of callingclosethread()
.it seems have memory problems. either whatever in
exportcorner()
uses alot of memory or create many threads @ once. andy turner has mentioned in comments, might usefull use executorservice handlerunnable
s. may managing threads , ensure limited thread count.
Comments
Post a Comment