views:

170

answers:

2

Sorry for another vague example...but I have a single class where I'm starting a new thread instance. However, if I add a new thread instance, it interrupts (destroys?) the first.

But, if I run two instances of the class (separately, after I turn them into jar files) where each instance only opens up a single thread, they both run concurrently and fine.

I'm convinced the error is the way I'm implementing multi-threading.

Any suggestions for things to look for? Thanks! Sorry for the vague example.

A: 

Ok, here's an example:

public class driver {

    public static void main(String args[])
    {
     Thread x;
     Thread y;

     x = new Thread(new pow());
     y = new Thread(new pow());

     x.start();
     y.start(); 
    }
}

public class pow extends Thread {

    public void run() {
     InstanceOfClassIDontControl a = new InstanceOfClassIDontControl();
                a.doVariousProcesses();
    }
}

In the example, I (obviously) don't control the class whose instance is created and called in the thread. Each thread may run for minutes. But whenever a concurrent thread is ran (in this case, with y.start()), it destroys the actions of the object called in the run() instance of x.start().

Monster
It sounds like InstanceOfClassIDontControl is not thread safe and uses global, static data structures. I would check the documentation of InstanceOfClassIDontControl.
Jason Coco
But is there no simple way of encapsulating it by itself? I can run as many instances as I want, so long as they are in different running jars.
Monster
Objects do not run in Jars. In normal Java when loading a class all the jars in the classpath are searched and the first definition od a class is loaded. Duplicating the class in many jars will make no difference. The probably answer is to provide a thread-safe wrapper around the non-thread-safe class.
djna
+3  A: 

You cannot assume that an arbitrary class is thread-safe.

Authors of a class should be explicit about the thread-safety of their classes, but it's very common that they do not. Given that environments such as Servlets may be intrinsically mulit-threaded this can be a real problem.

You need to study the class and discover which, if any, methods are thread safe. It is possible that the class InstanceOfClassIDontControl has static variables that are getting confused by multithreaded access. If you not only don't control the class, but can't even see its source then you are going to need the owners support.

djna