42
Chapter 2. First Steps in OSGi
2.11. Starting and Stopping Threads One of the things that we can do from the start method of a bundle activator is start a thread. Java makes this very easy, but the part that we must worry about is cleanly stopping our threads when the bundle is stopped. Listing 2.7 Heartbeat Activator 1
package org . osgi . tutorial ;
4
import org . osgi . framework . BundleActivator ; import org . osgi . framework . BundleContext ;
6
public class HeartbeatActivator implements BundleActivator {
3
private Thread thread ;
8
public void start ( BundleContext context ) throws Exception { thread = new Thread ( new Heartbeat ( ) ) ; thread . start ( ) ; }
10 11 12 13 15 16 17
public void stop ( BundleContext context ) throws Exception { thread . interrupt ( ) ; }
18
}
20
class Heartbeat implements Runnable {
22 23 24 25 26 27 28 29 30 31 32
}
public void run ( ) { try { while ( ! Thread . currentThread ( ) . isInterrupted ( ) ) { Thread . sleep (5000); System . out . println ( " I ’m still here . " ) ; } } catch ( InterruptedException e ) { System . out . println ( " I ’m going now . " ) ; } }
The code in Listing 2.7 shows a simple “heartbeat” thread that prints a message every five seconds. In this case, we can use Java’s interruption mechanism, which is a simple boolean status that can be set on a thread by calling the interrupt method. Unfortunately it is not always so easy to wake up a thread and ask it to stop, as we will see in Chapter 6.
2.12. Manipulating Bundles The OSGi framework gives us quite a lot of programmatic control over other bundles. Let’s look at an example in which we tie the lifecycle of a “target” bundle to its source file in the filesystem.
DRAFT PREVIEW prepared for Christopher Brind