Search code examples
javamultithreadinggetinstancerunnable

find instance by thread name java



I'm starting few threads in my Controller class. Before start each thread I want to check whether previously have I started MyClass run(). If I have started, then I need to find the instance of MyClass that is running. Because some other class also want to get done work from this same MyClass instance. (assume MyClass is running as a service. So it can have multiple requests coming in.)

Note that I have more than one MyClass instances running as threads. So I want to find the MyClass instance by Specific thread name(TH1 or TH2).

public class MyClass implements Runnable{
   public void run() { 
     .
     .
     .
   }
}

This is the class that start the threads.

public class Controller {
    private void threadStarter(int i) {
      MyClass  mclss;
      if (i==1) {

         mclss  = new MyClass();
         Thread   th     = new Thread(mclss , "TH1");
         th.start();

      } else {

         mclss  = new MyClass();
         Thread   th2    = new Thread(mclss , "TH2");
         th2.start();

      }
    }
} 

Solution

  • Java threads have an ID http://docs.oracle.com/javase/6/docs/api/java/lang/Thread.html#getId() . Maybe you could leverage that. However, if my application depends on previous instance, if any, running, then I would have an identifier in MyClass itself and then use it . e.g.

    class MyClass implements Runnable {
    
    int id = -1;
    
    public synchronized int getId() {
     if(id == -1) {
     id = SomeSingleTon.getNextId();
     }
     return id;
    }
    
    
    public run() ...
    //etc
    }
    

    And then in controller class you could check the instance ids, currently running. Maybe you will need a collection to store all running instances of MyClass. Hope you get the idea.