Constructing a thread when you don’t know the class ahead of time

While building a generic load testing toolkit, I found it useful to be able to use a standard invocation framework for running a thread class that contains the actual application code to be stress tested. However, I had some problems determining how to dynamically create a set of threads when I didn’t know the class ahead of time.

What is below is a simple framework to get you started.

public class loadUnknownThreadedClass {

  public static void main(String args[]) throws Exception{

    Thread[] threads = new Thread[5];

    Class tmp = Class.forName(args[0]);
    for(int i = 0;i < 5;i++) {
      threads[i] = new Thread((Runnable)tmp.newInstance());
      threads[i].start();
    }
  }
}

class classA implements Runnable {
  Thread t;

  classA() {
    t = new Thread(this);
  }
  public void run () {
    System.out.println("in classA");
  }
}

class classB implements Runnable {
  Thread t;

  classB() {
    t = new Thread(this);
  }
  public void run () {
    System.out.println("in classB");
  }
}

The really important piece is below:

     Class tmp = Class.forName(args[0]);
     threads[i] = new Thread((Runnable)tmp.newInstance());

This creates a class on the fly for what you want to dynamically run in a thread. It then casts a new instance of this to a Runnable object, which is required by the Thread class constructor.

Sample output is shown below.

emgrid01:oracle:emprod1:/home/oracle>java loadUnknownThreadedClass classA
in classA
in classA
in classA
in classA
in classA
emgrid01:oracle:emprod1:/home/oracle>java loadUnknownThreadedClass classB
in classB
in classB
in classB
in classB
in classB
emgrid01:oracle:emprod1:/home/oracle>

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.