As an example of the sharing of classes and data between MIDlets, suppose a MIDlet suite contains a class called Counter, intended to keep count of the number of instances of MIDlets from that suite are running at any given time.
public class Counter {
private static int instances;
public static synchronized void increment( ) {
instances++;
}
public static synchronized void decrement( ) {
instances--;
}
public static int getInstances( ) {
return instances;
}
}
Only a single instance of this class will be loaded in the Java VM, no matter how many MIDlets from the suite that supplies it are running in that VM. This means that the same static variable instances is used by all of these MIDlets, and, therefore the increment and decrement methods all affect the same counter. The fact that these methods are synchronized protects the instances variable from concurrent access by any threads in all of the MIDlets.

Reply With Quote

