Multitasking Guide Sun Java™ Wireless Client Software, Version 2.0 Java Platform, Micro Edition Sun Microsystems, Inc. www.sun.
Copyright © 2007 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, California 95054, U.S.A. All rights reserved. Sun Microsystems, Inc. has intellectual property rights relating to technology embodied in the product that is described in this document. In particular, and without limitation, these intellectual property rights may include one or more of the U.S. patents listed at http://www.sun.com/patents and one or more additional patents or pending patent applications in the U.S.
Contents Preface 1. ix Introduction 1 Multitasking 2 Robustness 3 Mechanisms Compared With Policies 2. Multitasking Safety 3 5 Multitask Safety and Multithread Safety Global and Static Data Singletons 7 8 Multitasking Safety Example Multithread Safety Multitask Safety 9 11 13 Establishing Per-Task Context 3.
Default Resource Allocation Policies 24 Customization of Resource Allocation Policies 4.
Code Samples CODE EXAMPLE 2-1 Native API for a Microwave Oven 9 CODE EXAMPLE 2-2 Typical usage of the microwave CODE EXAMPLE 2-3 Simple Java API for the Microwave Oven CODE EXAMPLE 2-4 Introducing a Locking Mechanism for Thread Safety CODE EXAMPLE 2-5 Using the Locking Mechanism CODE EXAMPLE 2-6 Migrating the Initialization Variable to Native Code (Doesn’t Work) CODE EXAMPLE 2-7 Migrating Initialization to Native Code CODE EXAMPLE 2-8 Keeping State in Java Code CODE EXAMPLE 2-9 Implementi
vi Multitasking Guide • May 2007
Tables TABLE 3-1 Constant Definitions for the Resource Management Policy 26 vii
viii Multitasking Guide • May 2007
Preface The Multitasking Guide highlights multitasking programming issues in the Sun Java™ Wireless Client software. It describes how to make code safe for the multitasking environment of the Java Wireless Client software. There is a special section about resource management. The Multitasking Guide also describes some multitasking policies implemented in the Java Wireless Client software and discusses possible alternatives.
Note – Note - Sun is not responsible for the availability of web sites mentioned in this document. Sun does not endorse and is not responsible or liable for any content, advertising, products, or other materials available through such sites. How This Guide Is Organized This book contains the following chapters: Chapter 1 provides an overview of the implementation and pitfalls of the Java Wireless Client software’s multitasking environment.
Application Title Multitasking Test Tools Multitasking Quality Test Suite Guide Viewing reference documentation created by the Javadoc™ tool Java API Reference Viewing reference documentation created by the Doxygen tool Native API Reference Typographic Conventions Used in This Guide Typeface Meaning Examples Courier AaBbCc123 The names of commands, files, and directories; on-screen computer output Edit your .login file. Use ls -a to list all files. % You have mail.
Accessing Sun Documentation Online The Java Developer Connection™ program web site enables you to access Java platform technical documentation at http://java.sun.com/. Sun Welcomes Your Comments We are interested in improving our documentation and welcome your comments and suggestions. Provide feedback to Sun at http://java.sun.com/docs/forms/sendusmail.html.
CHAPTER 1 Introduction Customers use mobile phones and other handheld devices for many tasks, such as making phone calls, taking photographs, playing games, organizing contact information, keeping a calendar of events, and accessing web sites. It is natural for them to want to do more than one of these tasks at a time. For example, a customer might not want to shut the address book to receive a flight-delay alert.
Multitasking The Connected Limited Device Configuration HotSpot™ Implementation can run multiple Java applications within a single operating system (OS) process. Historically, a CLDC virtual machine (VM) could run one Java application at a time, and each virtual machine typically required its own OS process. Running more than one Java application meant running more than one OS process. This could use too many resources on some small devices.
Robustness In addition to providing the multitasking that users want, tasks have the following benefits: ■ ■ Fault containment - If a Java application crashes, then any problems caused by this crash are limited to the task. Applications running in other tasks are unaffected. Clean termination - When a Java application exits, it leaves the virtual machine in a consistent state.
Because policies are so device dependent, this book does not recommend specific policy combinations. As you determine the policies for your device, keep in mind that policies interact with each other and not all combinations of policies make sense. For example, if you have a policy to allow a MIDlet to access a sound device while it is in the background, it does not make sense to also have a policy to suspend a MIDlet’s execution when it is in the background.
CHAPTER 2 Multitasking Safety The Java Wireless Client software provides the ability to run multiple MIDlets concurrently in a single OS process. From the standpoint of the OS, there is one process and one Java virtual machine. However, from the standpoint of a Java application, it appears as if it is running in its own, independent virtual machine, isolated from other Java applications. These apparently independent virtual machines are called tasks. Each MIDlet runs in its own task.
The following list summarizes the multitasking safety issues to consider when you update or add native code for your port: ■ ■ ■ Multitask safety and multithread safety Native global or static data Singletons Multitask Safety and Multithread Safety Many systems today are multithreaded, which requires code that runs in these systems to be thread safe or multithread safe. For example, POSIX Threads (Pthreads) enables multiple native threads to run in the same OS process.
For example, certain native functions (such as file storage) must be maintained on a per-application basis. In a single-tasking system, only one application is running, and so all file access is on behalf of that one application. In a multitasking system, several applications are running, and so the file access code can no longer assume that just one application exists.
Maintain the following invariants: ■ ■ A value of zero means a NULL pointer A nonzero value means a valid native pointer In native code, when you allocate memory, use KNI field access to store the pointer in the private field. When you free the native memory, use KNI field access to store 0 in the field. Using the K Native Interface (KNI) field access avoids race conditions. Have operations that use the native pointer use KNI field access for consistency.
You might find that you cannot organize the singleton’s maintenance in this way, because its state must be updated synchronously and atomically. Maintaining the foreground state is an example of this type of singleton. In this case, migrate a key piece of state into native memory and handle updates through calls to native methods. Multitasking Safety Example Consider a simple though somewhat contrived example of controlling an external device, a microwave oven.
*/ extern void mw_cook(MWCB callback, void *context); Typical usage of this API is shown in CODE EXAMPLE 2-2. Typical usage of the microwave void cb_popcorn(MWSTATUS status, void *context) { if (status == MW_INTERRUPTED) { /* tell the user that the popcorn isn't finished */ } else { ... } } CODE EXAMPLE 2-2 void cook_popcorn() { mw_init(); mw_settime(180); mw_setpower(100); mw_cook(cb_popcorn, NULL); } For the sake of discussion, assume that this native library is extremely simplistic.
Multithread Safety The most obvious problem with the interface defined in CODE EXAMPLE 2-3 is that it is not thread-safe. A single Java platform thread (Java thread) calling the APIs can certainly use it effectively, but if another thread attempts to use the API, things almost certainly break. For example, one thread might call setTime(). Another thread might be scheduled and issue a call to setTime() with a different value.
public static synchronized setPower(int power) { if (owner != Thread.currentThread()) { throw new IllegalStateException(); } n_setPower(power); } public static synchronized setTime(int nsecs) { if (owner != Thread.currentThread()) { throw new IllegalStateException(); } n_setTime(nsecs); } public static synchronized int cook() { if (owner != Thread.
This API is now multithread safe. However, it is not multitask safe. The reason is that the thread safety properties are achieved using mechanisms that belong to the Microwave class. These include static variables (initialized, owner) of the Microwave class. Thread synchronization and wait and notify operations use the monitor lock owned by the class. All of these mechanisms are visible to the threads of a single task, and thus they provide safety among the multiple threads of a single task.
Migrating the Initialization Variable to Native Code (Doesn’t Work) // Microwave.java CODE EXAMPLE 2-6 static native boolean getInitState(); static native void setInitState(boolean init); public static synchronized void lock() throws InterruptedException { ... if (!getInitState()) { init(); setInitState(true); } } Unfortunately, the code in CODE EXAMPLE 2-6 does not work. The reason is that threads from different tasks can be switched at any time.
{ if (initialized == 0) { initialized = 1; mw_init(); } KNI_ReturnVoid(); } Note that no mutual exclusion is necessary in native methods. The CLDC HotSpot Implementation has a single thread that runs all Java threads and all native methods. This thread can run at most one native method at a time. The system cannot contextswitch to another Java thread while it is in the midst of a native method. Therefore, in the CLDC HotSpot Implementation, all native methods are essentially critical sections.
The lock() and unlock() static methods were added to the Microwave class to protect the context that was being built implicitly in library static data by the setTime() and setPower() methods. This locking protocol effectively provides mutual exclusion around library static data. This works in a single-tasking environment, but it fails in a multitasking environment, as described earlier.
For the sake of simplicity, ignore the situation where another cooking operation might already be in progress, and ignore the logic for block and unblocking the calling thread. Note also the use of a technique for allocating a native context object and storing its pointer in a Java object field. All data used in this native method is relative to the Java object on which it’s called. This automatically provides multitask safety.
} else { /* this is a reinvocation after having been awakened */ statusp = (MWSTATUS *)KNI_GetIntField(thisObj, nativePtrFieldID); retval = (int)(*statusp); KNI_SetIntField(thisObj, nativePtrFieldID, 0); free(statusp); } KNI_EndHandles(); KNI_ReturnInt(retval); } void callback(MWstatus status, void *context) { MWSTATUS *statusp = (MWSTATUS *)context; *statusp = status; /* * Search the list of block threads and find the right * one to unblock with SNI_UnblockThread().
These examples show how multitask safety can be achieved by judicious migration of data from Java code into native code (for global singletons) and from native code into Java code (for context-specific data). Some libraries have explicit context objects, with all operations relative to that context object. For cases like that, a reliable technique is to put the native context pointer into a nativePtr int field in the Java object.
20 Multitasking Guide • May 2007
CHAPTER 3 Managing Native Resources The typical device is constrained in the amount of resources, such as memory or sockets, that it has available. When the Java Wireless Client software is running on a device, it is often provided with a fixed set of resources that it cannot exceed. In a single-tasking environment, a single MIDlet has access to all of the available resources. However, in a multitasking environment, multiple MIDlets might have to compete among themselves for this fixed set of resources.
The Java Wireless Client software solves this problem by providing a set of resource management mechanisms that can be used to control how resources are allocated. The Java Wireless Client software also provides a set of resource management policies that determine how the system behaves under certain conditions. These policies can be customized to tailor the behavior of the system for a particular deployment. Two example policies are also provided as a starting point for customization.
Many MIDlets are not designed to deal with failure in the midst of an operation. If such a MIDlet is updating one of its date structures when an allocation failure occurs, the date structure might end up in an inconsistent or corrupted state. Providing MIDlets with a resource reservation will prevent failures from occurring at arbitrary times, thus reducing the possibility of data structure corruption.
Revocation The revocation mechanism lets the system take a resource from one MIDlet to give the resource to another MIDlet. This second MIDlet is sometimes said to have preempted the resource from the first MIDlet. Resources are revoked without receiving any request from the MIDlet. The MIDlet might or might not be informed explicitly that the revocation is taking place, depending upon the type of resource being revoked. After allocation by a MIDlet, many resources are deallocated explicitly by the MIDlet.
behavior might be less confusing to the user than the failures that could happen with the open resource policy, because these failures are predictable. They always happen when the user tries to start the application. The default policy is open for competition. To use a fixed-partition resource policy, you must set a build-time flag USE_FIXED=true. See the Sun Java Wireless Client Build Guide for more information.
Each resource typically has five constants that define the policy. A pair of constants defines the reservation and the limit for each MIDlet suite. These constants have the suffixes SUITE_RESERVED and SUITE_LIMIT, respectively. Another pair of constants defines the reservation and limit for the AMS task. These constants have the suffixes AMS_RESERVED and AMS_LIMIT. Finally, the fifth constant specifies the global limit for the entire system.
Chapter 3 Managing Native Resources 27
28 Multitasking Guide • May 2007
CHAPTER 4 Other Multitasking Issues Multitasking raises some issues related to the behavior of the Java Wireless Client software. This chapter describes the issues, how they are handled by the Java Wireless Client software, and possible alternatives. Most of the issues discussed in this chapter relate to the implementation of the Java platform AMS. The same issues must be addressed by the Native AMS.
Default Policy The Java Wireless Client software supplies a default policy for how a MIDlet gains the foreground. It enables the user to switch to an application list screen at any time by pressing a hot key. By default, the hot key is the Home key found on many platforms. The application list screen shows a list of all running MIDlets. When the user brings up the application list, the MIDlet that had been in the foreground is moved into the background.
Default CPU Scheduling Policy By default, the Java Wireless Client software permits background applications to have some CPU time. A background application can also interrupt the foreground application under some circumstances. Specifically, the CPU scheduling policy is fair share, which gives a higher proportion of the CPU to the foreground application. Background applications can still run, but their threads are scheduled less frequently.
Interrupting the User Although a good user interface permits a user to interrupt applications at any time, it does not do the same to the user. Instead, it interrupts the user only when necessary. Unnecessary feedback, confirmation messages, and error messages that require a user response are distracting. See the MIDP 2.0 Style Guide (AddisonWesley, 2003) for more information.
Glossary API AMS Application list Background CDC Application Programming Interface. A set of classes used by programmers to write applications, which provide standard methods and interfaces and eliminate the need for programmers to reinvent commonly used code. Application Management Service. The system functionality that completes tasks such as installing applications, updating applications, and switching foregrounds. The screen that lists all of the installed applications.
GCF Home screen The main screen of the application manager. This is the screen the user sees after they exit an application. HTTP HyperText Transfer Protocol. The most commonly used Internet protocol, based on TCP/IP, which is used to fetch documents and other hypertext objects from remote hosts. HTTPS Secure HyperText Transfer Protocol. A protocol for transferring encrypted hypertext data using Secure Socket Layer (SSL) technology. JAD file Java Application Descriptor file.
LCDUI Liquid Crystal Display User Interface. A user interface toolkit for interacting with LCD screens in small devices. More generally, a shorthand way of referring to the MIDP user interface APIs. MIDlet An application written for MIDP. MIDlet suite MIDP Obfuscation Optional Package PNG Preemption Preverification A way of packaging one or more midlets for easy distribution and use. Each MIDlet suite contains a Java application descriptor file (.
RMS Record Management System. A simple record-oriented database that enables a MIDlet to persistently store information and retrieve it later. MIDlets can also use the RMS to share data. SMS Short Message Service. A protocol allowing transmission of short text-based messages over a wireless network. SOAP SSL Sun Java Device Test Suite Secure Sockets Layer.
Index C R CPU scheduling, 30 reservation, 22 resource allocation policy customization, 25 default, 24 revocation, 24 D data global, 7 static, 7 S F singletons, 8 foreground MIDlet switching, 29 T limit, 23 task, 2 context, 15 tasks, 2, 5 M U mechanisms compared with policies, 3 multitask safety, 13 multitasking, 2 multitasking safety, 5, 6 multithread safety, 6, 11 user notification, 32 L V virtual machine logical, 2 N native concurrency, 7 native resources, 21 P policies compared with me
38 Multitasking Guide • May 2007