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...

  1. when exception occurred in running thread - can't stop that. , when try make thread name "exceptionininitializererror" or "outofmemoryerror: java heap space" comes
  2. "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:

  1. you cannot join thread in itself. thread.join() waits until thread dies. if call thread want stop, waits forever.

  2. to stop thread have return run() method. in case, add return in catch clause instead of calling closethread().

  3. 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 handle runnables. may managing threads , ensure limited thread count.


Comments

Popular posts from this blog

java - Suppress Jboss version details from HTTP error response -

gridview - Yii2 DataPorivider $totalSum for a column -

Sass watch command compiles .scss files before full sftp upload -