Quote:
Originally Posted by olakara
Hi,
I tried starting the bundle by calling myThread.start().. i noticed that, the state of the bundle to not change from STARTING to ACTIVE :-(
|
Sorry, perhaps I wasn't clear enough - in the code you posted you are using the myThread.run() method, which simply executes your runnable code in the current thread (ie. the framework thread calling your bundle start method). This means your bundle state will stay as STARTING, because your bundle start method never returns (you can add a println to show this).
If you change this to be myThread.start() then the JVM will execute your runnable code in a new Java thread separate to the framework thread, and your start method will return as expected (for more background on starting threads, see the
javadoc for Thread.start() compared to Thread.run()).
I've just tested this change locally on Equinox and Felix (another OSGi framework) and can start and stop your example bundle without error.
Here's the working code, where I've only changed one line:
Code:
package threadbundle;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
public class Activator implements BundleActivator {
private Thread myThread;
private CustomThread cTObject;
public void start(BundleContext context) throws Exception {
System.out.println("Starting ThreadBundle...");
cTObject = new CustomThread();
myThread = new Thread(cTObject);
myThread.start(); // !! use start() to fork a new thread !!
}
public void stop(BundleContext context) throws Exception {
if(myThread.isAlive())
cTObject.stopTheThread();
System.out.println("Stopping thread bundle..");
}
private class CustomThread implements Runnable {
boolean stopper;
CustomThread() {
stopper = false;
}
public void stopTheThread(){
if(!stopper)
stopper = true;
}
public void run() {
try {
while(!stopper) {
System.out.println("Message from thread...");
Thread.sleep(5000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
You might want to check that you're definitely deploying the new version of the code - have you restarted the framework, or just updated the bundle? If you updated it, what commands did you use? BTW, if all else fails you could always clear out the bundle cache and do a fresh deployment with the new code, if you're not sure which version you're running...