Sun Microsystems 2 Manuel utilisateur

Taper
Manuel utilisateur

Ce manuel convient également à

Sun Microsystems, Inc.
www.sun.com
Multitasking Guide
Sun Java™ Wireless Client Software, Version 2.0
Java Platform, Micro Edition
May 2007
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. and in other countries.
THIS PRODUCT CONTAINS CONFIDENTIAL INFORMATION AND TRADE SECRETS OF SUN MICROSYSTEMS, INC. USE,
DISCLOSURE OR REPRODUCTION IS PROHIBITED WITHOUT THE PRIOR EXPRESS WRITTEN PERMISSION OF SUN MICROSYSTEMS,
INC.
U.S. Government Rights - Commercial software. Government users are subject to the Sun Microsystems, Inc. standard license agreement and
applicable provisions of the FAR and its supplements.
This distribution may include materials developed by third parties.
Sun, Sun Microsystems, the Sun logo, Java, Solaris, HotSpot, J2ME, J2SE, Java Developer Connection, Java Community Process, JCP, Javadoc,
JDK, JavaCall, phoneME and the Java Coffee Cup logo are trademarks or registered trademarks of Sun Microsystems, Inc. in the U.S. and other
countries.
UNIX is a registered trademark in the U.S. and other countries, exclusively licensed through X/Open Company, Ltd.
Intel is a trademark or registered trademark of Intel Corporation or its subsidiaries in the United States and other countries.
OpenGL is a registered trademark of Silicon Graphics, Inc.
The Adobe logo and the PostScript logo are trademarks or registered trademarks of Adobe Systems, Incorporated.
Products covered by and information contained in this service manual are controlled by U.S. Export Control laws and may be subject to the
export or import laws in other countries. Nuclear, missile, chemical biological weapons or nuclear maritime end uses or end users, whether
direct or indirect, are strictly prohibited. Export or reexport to countries subject to U.S. embargo or to entities identified on U.S. export exclusion
lists, including, but not limited to, the denied persons and specially designated nationals lists is strictly prohibited.
DOCUMENTATION IS PROVIDED “AS IS” AND ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES,
INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT,
ARE DISCLAIMED, EXCEPT TO THE EXTENT THAT SUCH DISCLAIMERS ARE HELD TO BE LEGALLY INVALID.
Copyright © 2007 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, California 95054, Etats-Unis. Tous droits réservés.
Sun Microsystems, Inc. détient les droits de propriété intellectuels relatifs à la technologie incorporée dans le produit qui est décrit dans ce
document. En particulier, et ce sans limitation, ces droits de propriété intellectuelle peuvent inclure un ou plus des brevets américains listés à
l’adresse http://www.sun.com/patents et un ou les brevets supplémentaires ou les applications de brevet en attente aux Etats - Unis et dans les
autres pays.
CE PRODUIT CONTIENT DES INFORMATIONS CONFIDENTIELLES ET DES SECRETS COMMERCIAUX DE SUN MICROSYSTEMS, INC.
SON UTILISATION, SA DIVULGATION ET SA REPRODUCTION SONT INTERDITES SANS L’AUTORISATION EXPRESSÉE, ECRITE ET
PRÉALABLE DE SUN MICROSYSTEMS, INC.
Droits du gouvernement des États-Unis logiciel commercial.Les droits des utilisateur du gouvernement des États-Unis sont soumis aux
termes de la licence standard Sun Microsystems et aux conditions appliquées de la FAR et de ces compléments.
Cette distribution peut inclure des elements développés par des tiers.
Sun, Sun Microsystems, le logo Sun, Java, Solaris, HotSpot, J2ME, J2SE, Java Developer Connection, Java Community Process, JCP, Javadoc,
JDK, JavaCall, phoneME et le logo Java Coffee Cup sont des marques de fabrique ou des marques déposées de Sun Microsystems, Inc. aux Etats-
Unis et dans d’autres pays.
UNIX est une marque déposée aux Etats-Unis et dans d'autres pays et sous license exclusive de X/Open Company, Ltd.
Intel est une marque déposée de Intel Corporation ou de sa filiale aux Etats-Unis et dans d'autres pays.
OpenGL est une marque déposée de Silicon Graphics, Inc.
Le logo Adobe et le logo PostScript sont des marques de fabrique ou des marques déposées de Adobe Systems, Incorporated.
Les produits qui font l’objet de ce manuel d’entretien et les informations qu’il contient sont regis par la législation américaine en matière de
contrôle des exportations et peuvent être soumis au droit d’autres pays dans le domaine des exportations et importations. Les utilisations
finales, ou utilisateurs finaux, pour des armes nucléaires, des missiles, des armes biologiques et chimiques ou du nucléaire maritime,
directement ou indirectement, sont strictement interdites. Les exportations ou réexportations vers des pays sous embargo des Etats-Unis, ou
vers des entites figurant sur les listes d’exclusion d’exportation américaines, y compris, mais de manière non exclusive, la liste de personnes qui
font objet d’un ordre de ne pas participer, d’une façon directe ou indirecte, aux exportations des produits ou des services qui sont régis par la
législation américaine en matière de contrôle des exportations et la liste de ressortissants spécifiquement désignés, sont rigoureusement
interdites.
LA DOCUMENTATION EST FOURNIE "EN L’ÉTAT" ET TOUTES AUTRES CONDITIONS, DÉCLARATIONS ET GARANTIES EXPRESSÉS
OU TACITES SONT FORMELLEMENT EXCLUES, DANS LA MESURE AUTORISÉ PAR LA LOI APPLICABLE, Y COMPRIS NOTAMMENT
TOUTE GARANTIE IMPLICITE RELATIVE À LA QUALITÉ MARCHANDE, À L’APTITUDE À UNE UTILISATION PARTICULIÈRE OU A
L’ABSENCE DE CONTREFAÇON.
iii
Contents
Preface ix
1. Introduction 1
Multitasking 2
Robustness 3
Mechanisms Compared With Policies 3
2. Multitasking Safety 5
Multitask Safety and Multithread Safety 6
Global and Static Data 7
Singletons 8
Multitasking Safety Example 9
Multithread Safety 11
Multitask Safety 13
Establishing Per-Task Context 15
3. Managing Native Resources 21
Resource Management Mechanisms 22
Reservation 22
Limit 23
Revocation 24
iv Multitasking Guide May 2007
Default Resource Allocation Policies 24
Customization of Resource Allocation Policies 25
4. Other Multitasking Issues 29
Switching the Foreground MIDlet 29
Default Policy 30
Alternative Policies and Their Implementations 30
Scheduling the CPU 30
Default CPU Scheduling Policy 31
Alternative Policies and Their Implementations 31
Interrupting the User 32
Default User Notification Policies 32
Glossary 33
Index 37
v
Code Samples
CODE EXAMPLE 2-1 Native API for a Microwave Oven 9
CODE EXAMPLE 2-2 Typical usage of the microwave 10
CODE EXAMPLE 2-3 Simple Java API for the Microwave Oven 10
CODE EXAMPLE 2-4 Introducing a Locking Mechanism for Thread Safety 11
CODE EXAMPLE 2-5 Using the Locking Mechanism 12
CODE EXAMPLE 2-6 Migrating the Initialization Variable to Native Code (Doesn’t Work) 14
CODE EXAMPLE 2-7 Migrating Initialization to Native Code 14
CODE EXAMPLE 2-8 Keeping State in Java Code 16
CODE EXAMPLE 2-9 Implementing the Native n_cook() Method 17
vi Multitasking Guide May 2007
vii
Tables
TABLE 3-1 Constant Definitions for the Resource Management Policy 26
viii Multitasking Guide May 2007
ix
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 Sun Microsystems has simplified the naming schemes for the various Java
platforms. Java Platform, Enterprise Edition (Java EE) was formerly Java 2 Platform,
Enterprise Edition (J2EE™). Java Platform, Standard Edition (Java SE) was formerly
Java 2 Platform, Standard Edition (J2SE™), and Java Platform, Micro Edition (Java
ME) was formerly Java 2 Platform, Micro Edition (J2ME™).
References in this guide to specific documents, specifications, and products that
were released when the old naming scheme was in use retain their original names.
General references in this guide to Java platforms use the new, simplified naming
scheme.
Before You Read This Guide
Readers using this guide must be familiar with the MIDP 2.1 Specification. The
specification is available from http://www.jcp.org/. It is also useful if the reader
is familiar with the Java Wireless Client software code.
x Multitasking Guide May 2007
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.
Chapter 2 describes how source code can be made safe for multitasking.
Chapter 3 covers strategies and implementations for managing device resources.
Chapter 4 includes a brief overview of the multitasking policies and alternatives in
the Java Wireless Client software.
Related Documentation
The following documentation is included with this release of the Java Wireless
Client software:
Application Title
All Release Notes
Building the Sun Java Wireless Client software Build Guide
Porting the Sun Java Wireless Client software Porting Guide
Porting implementations of optional Java Specification Requests
(JSRs)
Optional Packages
Porting Guide
Creating a new Adaptive User Interface (skin) for the Java
Wireless Client software
Skin Authors Guide to
Adaptive User Interface
Technology
Configuration and Testing Tools Tools Guide
Preface xi
Typographic Conventions Used in This
Guide
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
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.
Bold
AaBbCc123
What you type, when
contrasted with on-screen
computer output
Important parts of a code
sample
%
su
Password:
Italic
AaBbCc123
Book titles, new words or terms,
words to be emphasized
Command-line variable; replace
with a real name or value
Read Chapter 6 in the Users Guide.
These are called class options.
You must be super user to do this.
To delete a file, type rm filename.
Application Title
xii Multitasking Guide May 2007
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.
1
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. The Java
Wireless Client software, which can concurrently run multiple MIDlets, meets this
need.
Device manufacturers and service providers also benefit from being able to run
multiple MIDlets concurrently. This functionality enables them to write built-in
(resident) applications, such as address books, in the Java programming language.
Applications written in the Java programming language (Java applications) are
easier to write and maintain, more portable, and easier to customize than those
written in native code. The Java Wireless Client software meets this need too.
In addition, the Java Wireless Client software enables MIDlet writers to take
advantage of multitasking without changing their code. MIDlet suites that run in the
Java Wireless Client software’s multitasking environment are no different from any
other MIDlets: They have no new APIs and they have the same life cycle. The MIDP
2.1 Specification advises all MIDlet writers about managing resources when the
MIDlet is paused and resumed. In a multitasking environment, a MIDlet might
compete with other MIDlets for resources, so it is more important than ever for
MIDlet writers to follow that advice and to use resources carefully.
2 Multitasking Guide May 2007
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. The multitasking feature enables a single
virtual machine, in a single OS process, to function as multiple virtual machines.
From the standpoint of each Java application, it is running in a separate virtual
machine.
When a MIDlet exits or encounters an error, it always leaves the virtual machine in a
consistent state. This works because each MIDlet is isolated from other MIDlets that
might also be running at the same time. If the MIDlets were not isolated from each
other, an error in one MIDlet might be visible to other MIDlets. This might result in
deadlock or crashes caused by corrupted data structures.
Multitasking, then, runs multiple logical virtual machines within a single OS
process. The CLDC HotSpot Implementation enables this by providing fundamental
mechanisms in the virtual machine. Mechanisms include threads, the isolation of
objects in the Java runtime environment (Java objects) belonging to different
programs, and safe termination. See the CLDC HotSpot Implementation Virtual
Machine White Paper at http://java.sun.com/j2me/docs/pdf/CLDC-
HI_whitepaper-February_2005.pdf for more information.
The OS mechanisms are important and necessary, but they aren’t sufficient to
provide a complete application environment. A complete system needs mechanisms
for managing the application life cycle (starting, stopping, and switching between
applications) and for enabling the user to control the application life cycle. It also
needs mechanisms for managing competition for limited shared resources, such as
memory and network sockets, among multiple applications. The Java Wireless Client
software provides all of these additional mechanisms.
The Java Wireless Client software is a high-performance, feature-rich, deployment-
ready implementation of Java Technology for the Wireless Industry that takes
advantage of the multitasking functionality in the CLDC HotSpot Implementation.
The logical virtual machines in the Java Wireless Client software are called tasks .
Each application has its own task. The Application Management System (AMS) runs
at all times in its own task. This architecture provides improved performance and
robustness.
Chapter 1 Introduction 3
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. In the past, some have tried to run multiple Java applications
in a single process by running the applications in separate threads within a single
virtual machine. When applications share a virtual machine, it is impossible to
guarantee that an application can exit cleanly, because objects might be left in an
inconsistent state. In contrast, tasks can and do terminate cleanly.
Note that in MIDP, a Java application is a MIDlet suite. A MIDlet suite is one or
more MIDlets in the same Java Archive (JAR) file. Each MIDlet suite, then, runs in its
own task. The user interacts with one of the MIDlets in the MIDlet suite.
Mechanisms Compared With Policies
Mechanisms are actions that the system carries out, such as starting, pausing, and
stopping a MIDlet. Policies are the system-wide decisions that device manufacturers
and service providers make about when and how to use the available mechanisms.
Policies take generic mechanisms and combine them into a predictable set of system
behaviors.
The Java Wireless Client software provides both the necessary mechanisms for a
complete application environment, such as mechanisms for managing competition
for limited shared resources, and a default set of policies. For example, memory is a
limited shared resource for which the Java Wireless Client software provides
mechanisms and a few default policies. The mechanism is the allocation of heap
memory. One default policy is to allow the applications to compete for available
heap memory.
The default policies are useful, but device manufacturers and service providers are
likely to need to tailor policies to their particular platforms. Devices of different
capabilities might use different policies. Devices with different user interface styles
might use different policies so that their Java applications interact with users in
ways that match the native applications interactions. Because policy decisions are
often intertwined with user interface style and user model decisions, the Java
Wireless Client software enables the development of alternative policies.
4 Multitasking Guide May 2007
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.
5
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. When a new MIDlet is started, a new task is created for it. When a
MIDlet exits, its task is destroyed. The Application Management Software (AMS)
runs in a dedicated task, and it is running the entire time the Java Wireless Client
software is active.
Although tasks cannot interact (they cannot access each other’s objects, for example),
they do share native code, process resources, and external resources. This sharing
leads to some implementation issues, both in native code and in Java programming
language code (Java code). The Java Wireless Client software takes these issues into
account. Those who want to integrate existing libraries, which might not have been
written with multitasking in mind, also need to be aware of the issues so that they
can add the source code correctly.
Code integrated into the Java Wireless Client software must be multitask safe. That is,
it must maintain the independence of one task from another. Because tasks run in a
single operating system process, the OS process can run native code for any task. To
keep tasks from interfering with each other and with each other’s data, the code
must be made aware of the task on whose behalf it is being called and possibly
allocating resources. When the task context is established, the code is considered
multitask safe.
This chapter points out issues that might arise in ensuring native code is multitask
safe. It also provides techniques for making the code multitasking safe in different
situations.
6 Multitasking Guide May 2007
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. Each native thread
has access to native memory, so any data structures in native memory must be
protected from concurrent access. This is typically accomplished through the use of
locks to provide mutual exclusion.
Similarly, multiple Java platform threads can run in the same Java virtual machine.
Each Java platform thread has access to the objects in the Java virtual machine, so
these objects must also be protected from concurrent access. Java code typically
accomplishes this through the use of synchronized code blocks or higher-level
constructs.
In the Java Wireless Client software, each task has one or more threads. Each of these
threads has concurrent access to the objects in that task, and so the same multithread
safety issues occur in Java Wireless Client software as in conventional Java virtual
machines. However, a thread in one task has access only to objects within its task,
and it has no access to objects in any other task. The multitasking nature of Java
Wireless Client software thus has no impact on the multithreaded safety of
applications.
All of the tasks in Java Wireless Client software run in a single OS process, and
therefore they all have access to the same native memory and data structures.
Threads from different tasks are scheduled arbitrarily. Therefore, native methods
that read or update native data structures must be prepared to deal with operations
from different tasks being interleaved in an arbitrary order. Furthermore, because
different tasks are generally running different applications, these different
applications are likely to place quite different demands on the underlying native
system.
Chapter 2 Multitasking Safety 7
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. Instead, it must be aware of the possibility of
multiple applications, so that one application doesn't accidentally operate on
another application’s files. Code that is aware of this possibility is multitask safe.
While operations from different tasks can occur in an arbitrary order, no possibility
exists of actual concurrency among native methods. One native thread exists in the
Java Wireless Client software. When it is running a native method, no possibility
exists of a context switch that causes another native method to be run at the same
time. Each native method runs to completion and returns before the next native
method can begin. For this reason, every native method is a critical section, and it is
usually not necessary to perform any OS-level locking (such as with Pthreads
mutexes) in native methods. It is only necessary to use OS-level locking if other
native threads are active in the system while the Java Wireless Client software is
running.
Thus, while native code that runs within Java Wireless Client software must be
multitask safe, it need not be multithread safe.
Global and Static Data
In a single-tasking system, it is common for native code to use global or static
variables. This works because only one application is running at a time. Global data
is implicitly associated with the currently running application. In a multi-tasking
system, the multiple applications likely conflict over global data. Therefore, to make
your code multitask safe, you might need to rearrange your native data to be
allocated on a per-task basis instead of globally.
To do this, you must allocate native data dynamically instead of statically. In
addition, you need to associate each piece of native data with a particular task.
To manage native data on a per-task basis, store a pointer to the native data into an
int field in a Java object. Associating the native resource with a single Java object
implicitly provides multitasking safety because each Java object resides in exactly
one task. It is also a good object-oriented approach.
Create a class to represent the native resource. Give the class a private field to hold
the pointer to the resource, for example:
private int nativePtr;
8 Multitasking Guide May 2007
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.
Have those operations check for a NULL value before they use the pointer, and throw
an appropriate exception if the field does not have a pointer. An appropriate
exception is a NullPointerException.
Singletons
CLDC HotSpot Implementation 2.0 isolates the logical virtual machines, but there is
one situation to consider if you add or change Java code: Singletons. Singleton
classes are often used when only one instance of a class should exist. Sometimes the
class itself is used as a singleton, and no instance of it is ever created. The way to
handle singleton depends on whether you mean it to be used on a per-application
(that is, per-task) basis or whether you mean it to be used by the entire system.
For example, in Java Wireless Client software, an event queue is a per-task singleton,
because each task has its own event queue. Per-task singletons are not a problem as
they are handled by the VM. Static state is automatically replicated on a per-task
basis. On the other hand, the singleton that holds the foreground display is a
system-global singleton. Only one Display can be in the foreground in the entire
system. All other display instances must be in the background. System-global
singletons require additional work.
To handle a system-global singleton, consider either maintaining the singleton’s state
in a single task (such as the AMS task) and communicate the updates through
messages, or migrating key pieces of information into native memory, with access to
them arbitrated through native methods.
If you maintain the singleton’s state in a single task and update it using events, be
aware that events are asynchronous messages. Organize the updates so that
operations are tolerant of being executed out of order. Although messages are
generally processed in the order received, messages from different tasks might not
be processed in the order they are sent. Also organize the updates so that requestors
can proceed asynchronously. Asynchronous messages do not have any
acknowledgement by default, so the sender cannot know when the message is
processed or whether it is processed successfully.
  • Page 1 1
  • Page 2 2
  • Page 3 3
  • Page 4 4
  • Page 5 5
  • Page 6 6
  • Page 7 7
  • Page 8 8
  • Page 9 9
  • Page 10 10
  • Page 11 11
  • Page 12 12
  • Page 13 13
  • Page 14 14
  • Page 15 15
  • Page 16 16
  • Page 17 17
  • Page 18 18
  • Page 19 19
  • Page 20 20
  • Page 21 21
  • Page 22 22
  • Page 23 23
  • Page 24 24
  • Page 25 25
  • Page 26 26
  • Page 27 27
  • Page 28 28
  • Page 29 29
  • Page 30 30
  • Page 31 31
  • Page 32 32
  • Page 33 33
  • Page 34 34
  • Page 35 35
  • Page 36 36
  • Page 37 37
  • Page 38 38
  • Page 39 39
  • Page 40 40
  • Page 41 41
  • Page 42 42
  • Page 43 43
  • Page 44 44
  • Page 45 45
  • Page 46 46
  • Page 47 47
  • Page 48 48
  • Page 49 49
  • Page 50 50

Sun Microsystems 2 Manuel utilisateur

Taper
Manuel utilisateur
Ce manuel convient également à

dans d''autres langues