100% found this document useful (1 vote)
11K views732 pages

Java Programming On Linux

Uploaded by

api-3839016
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
11K views732 pages

Java Programming On Linux

Uploaded by

api-3839016
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 732

Release Team[oR] 2001

[x] java [x] linux


Java Programming on Linux
by Nathan Meyers ISBN: 1571691669

Waite Group Press © 2000, 907 pages


This extensive reference will introduce you to the myriad
tools, technologies, and techniques that you'll need for
programming Java on Linux.

Table of Contents
Back Cover

Synopsis by Rebecca Rohan

This book is neither a course in Java programming nor a manual for the Linux
OS. While the well-written text provides overviews of both Java and Linux, it's
really a compendium of information you'll want on hand once you've chosen
Java-on-Linux. Coverage includes: configuring your Linux desktop, a list of the
Java core classes, a rundown of compilers, the Kaffe cleanroom, tidbits about
Linus Torvalds and Richard Stallman, the Open Source movement, when JIT
compilers are a benefit, threads, GNU, what's supported where, decompilers
and obfuscators, and improved graphical rendering. This must-have book will
answer your questions and provide enjoyable browsing for a long time

Table of Contents

Java Programming on Linux - 5


Linux and Java - The Choice of a New Millennium - 7
Part I A Brief Introduction to Java

Chapter 1 - What Is Java? - 12


Chapter 2 - Moving from C++ to Java - 19
Chapter 3 - A Look at the Java Core Classes - 36
Chapter 4 - Additional Sun Java Class Library Specs - 149
Part II A Brief Introduction to Linux

Chapter 5 - What Is Linux? - 155


Chapter 6 - How to Obtain and Install Linux - 162
Chapter 7 - Configuring Your Linux Desktop - 168
Chapter 8 - Installing Additional Linux Software - 173
Part III Setting Up for Java Development and Deployment on Linux

Chapter 9 - Setting Up a Linux Development Environment - 178


Chapter 10 - Java Components for Linux - 191
Chapter 11 - Choosing an Environment: 1.1 or 1.2? - 196
Chapter 12 - Software Licensing - 201
Part IV The Blackdown Port: A Sun Java SDK for Linux

Chapter 13 - Blackdown: The Official Linux Portx - 205


Chapter 14 - Configuring the Linux SDK/JRE Environment - 213

-2-
Chapter 15 - Troubleshooting the Blackdown JRE/JSDK Installation - 238
Chapter 16 - Participating in the Blackdown Community - 247
Part V Tools in the Blackdown JSDK

Chapter 17 - The Java Application Launchers: java, jre, and oldjava - 250
Chapter 18 - The Java Applet Viewer: appletviewer - 256
Chapter 19 - The Java Compiler: javac - 260
Chapter 20 - The Java Debugger: jdb - 263
Chapter 21 - The Java Archiver: jar - 268
Chapter 22 The Java Native Code Header and Stub File Generator:
-
javah - 270
Chapter 23 - The Java Documentation Generator: javadoc - 272
Chapter 24 - Miscellaneous JSDK Development Tools - 281
Part VI Additional Java Runtime Environments

Chapter 25 - The IBM JSDK Port - 292


Chapter 26 - Kaffe: A Cleanroom Java Environment - 293
Chapter 27 - Japhar: A Cleanroom JVM - 299
Chapter 28 - GNU Classpath: Cleanroom Core Class Libraries - 304
Chapter 29 - Mozilla ElectricalFire: A New JVM - 305
Chapter 30 - Sun HotSpot Performance Engine - 309
Chapter 31 - gcj: A Compiled Java Solution - 311
Chapter 32 - Tower: A Server-Side Hybrid Java Environment - 316
Part VII Additional Java Runtime Components

Chapter 33 - Just-In-Time Compilers - 325


Chapter 34 - Java3D Extension - 330
Chapter 35 JavaComm, JCL, and RXTX: Serial Communications from
-
Java - 340
Part VIII Compilers and Debuggers

Chapter 36 - The Jikes Compiler - 345


Chapter 37 - KJC: Kopi Java Compiler - 348
Chapter 38 - Generic Java Compilers - 351
Chapter 39 - The Jikes Debugger - 362
Chapter 40 - DDD: The Data Display Debugger - 366
Part IX IDEs, GUI Builders, and RAD Tools

Chapter 41 - vTcLava: A tcl-Based Java GUI Builder - 372


Chapter 42 - Korfe: A Python-Based Java GUI Builder - 379
Chapter 43 - PlaceHoldr IDE - 384
Chapter 44 - The Emacs JDE - 395
Chapter 45 - ArgoUML Modeling Tool - 405
Part X Miscellaneous Development Tools

Chapter 46 - Jad: A Java Decompiler - 412


Chapter 47 - DumpClass: A Tool for Querying Class Structure - 416
Chapter 48 - JMakeDepend: A Project Build Management Utility - 419
Part XI Java Application Distribution

Chapter 49 - Distributing Java Applications and JREs - 426

-3-
Chapter 50 - Deploying Applets with Java Plug-in - 429
Chapter 51 Crossing Platform Component Models: Bringing Java to
-
ActiveX - 439
Chapter 52 - InstallShield: Creating Self-Installing Java Applications - 456
Chapter 53 - DashO: Optimizing Applications for Delivery - 459
Part XII Linux Platform Issues

Chapter 54 - Java, Linux, and Threads - 469


Chapter 55 - JNI: Mixing Java and Native Code on Linux - 477
Chapter 56 - X Window System Tips and Tricks - 493
Part XIII Java Performance

Chapter 57 - Why Is Java Slow? - 508


Chapter 58 - A Heavy Look at Lightweight Toolkits - 519
Chapter 59 An Approach to Improving Graphical Rendering
-
Performance - 529
Chapter 60 - PerfAnal: A Free Performance Analysis Tool - 543
Chapter 61 - Heap Analysis Tool: Understanding Memory Utilization - 551
Chapter 62 - OptimizeIt: Live Performance Analysis - 554
Chapter 63 - Understanding Linux Kernel Performance - 560
Chapter 64 - Profiling User-Space Native Code - 568
Part XIV Java and Linux on Servers

Chapter 65 - Java on the Web: Java Servlets and Apache JServ - 574
Chapter 66 - Java from Web Pages: JSSI and JSP - 588
Chapter 67 - Java, Linux, and Three-Tiered Architectures - 560
Part XV Appendixes

Appendix A - Index of Tools and Programs - 607


Appendix B - Miscellaneous Program Listings - 611
Appendix C - Important Information Resources - 727
Appendix D - Tools Not Covered - 729

Back Cover
Java Programming on Linux is your guide to using the Java programming
language on the Linux platform. Written by an experienced Java and Linux
developer, this book introduces you to the many Java technologies available
today for you to use under Linux -- from proprietary Sun technologies to fully
Open Source solutions. Filled with practical, hands-on advice, Java
Programming on Linux will help you get the most out of Java and Linux, as an
applications platform, a development environment, and an enterprise server.

With Java Programming on Linux, you will learn:

• How to install, configure, troubleshoot, and use Sun’s Java


Development Kit on the Linux operating system.
• How to use many of the Java runtime and development environments
(from Sun and elsewhere) available for Linux.
• How to develop on Linux and distribute your applications to users on
all operating systems.
• How to access the unique capabilities of Linux and the X Window
System from Java.

-4-
• How to identify performance bottlenecks that are slowing down your
Java applications on Linux and other platforms.
• How to deploy Java on Linux servers to support three-tier application
architectures.

About the Author

Nathan Meyers spent 20 years as a software developer and architect with


Hewlett-Packard Company, working on platforms ranging from embedded
systems to large UNIX servers. His development background includes
operating systems, development tools, device drivers, tools for performance
tuning, graphics applications, and GUIs. Nathan was part of the HP team that
did pioneering work on the X Window Systems, the Motif Toolkit, and the
Common Desktop Environment. He has been working with Linux since 1995
and with Java on Linux since the early Linux JDK1.1 platform releases.

Java Programming on Linux

Nathan Meyers

Associate Publisher: Michael Stephens

Acquisitions Editor: Don Roche

Development Editor: Robyn Thomas

Managing Editor: Charlotte Clapp

Copy Editor: Geneil Breeze

Indexer: Joy Dean Lee

Proofreaders: Tony Reitz, Wendy Ott

Technical Editors: Luke Jones, Michael Jarvis, Juan Jose Sierralta P.

Team Coordinator: Pamalee Nelson

Media Developer: Todd Pfeffer

Interior Design: Gary Adair

Cover Design: Alan Clements

Copy Writer: Eric Borgert

Layout Technicians: Steve Geiselman. Brad Lenser

Copyright © 2000 by Waite Group Press

-5-
All rights reserved. No part of this book shall be reproduced, stored in a retrieval system,
or transmitted by any means, electronic, mechanical, photocopying, recording, or
otherwise, without written permission from the publisher. No patent liability is assumed
with respect to the use of the information contained herein. Although every precaution
has been taken in the preparation of this book, the publisher and author assume no
responsibility for errors or omissions. Neither is any liability assumed for damages
resulting from the use of the information contained herein.

International Standard Book Number: 1-57169-166-9

Library of Congress Catalog Card Number: 99-65624

Trademarks
All terms mentioned in this book that are known to be trademarks or service marks have
been appropriately capitalized. Waite Group Press cannot attest to the accuracy of this
information. Use of a term in this book should not be regarded as affecting the validity of
any trademark or service mark.

Warning and Disclaimer


Every effort has been made to make this book as complete and as accurate as possible,
but no warranty or fitness is implied. The information provided is on an "as is" basis. The
authors and the publisher shall have neither liability nor responsibility to any person or
entity with respect to any loss or damages arising from the information contained in this
book or from the use of the CD or programs accompanying it.

About the Author


Nathan Meyers spent 20 years in the corporate software trenches, as a developer and
architect for Hewlett-Packard Company, working in handheld calculators, UNIX
workstations, and inkjet printers. His experience includes development of embedded
systems, device driver implementation, creation of development tools, definition and
implementation work on the X Window System and the Common Desktop Environment,
development of 2D and 3D graphics applications, UNIX application performance tuning,
design of evolutionary algorithms, and implementation of financial algorithms.

Nathan left HP in 1999 to pursue other opportunities in the worlds of Linux and Java.
Besides books like this, he has published in the Hewlett-Packard Journal, The X Resource
Journal, and the Linux Journal. He participates actively in the Java/Linux community and
manages this book's Web site at http://www.javalinux.net—visit the site for
information, updates, errata, or just to send email to the author.

Dedication
To Vicki.

Acknowledgments
It takes a village to make a book, and this book has benefited from the talents of many
important contributors.

First, I'd like to thank Margot Maley of Waterside Productions and Don Roche of
Macmillan Computer Publishing, who worked together to bring this project into existence.
Development editor Robyn Thomas and project editor Charlotte Clapp coordinated the
complex logistics required to turn my words into a real book. Copy editor Geneil Breeze

-6-
kept my use of the language honest, and technical editors Luke Jones, Michael Jarvis,
and Juan Jose Sierralta P. checked my work on the technical side. To anyone else I've
neglected to mention: My sincere gratitude and my apologies for the oversight.

Beyond the efforts that went into creating this book, I must also acknowledge the heroic
efforts in the Java, Linux, and Open Source communities that have made this book both
possible and of value. To the many brilliant developers behind the Blackdown organization,
Transvirtual Technologies, Cygnus Solutions, IBM AlphaWorks, and many other
organizations mentioned in the book: Thank you for making Java on Linux a great place to
do software and a great place to do business.

Tell Us What You Think!


As the reader of this book, you are our most important critic and commentator. We value
your opinion and want to know what we're doing right, what we could do better, what
areas you'd like to see us publish in, and any other words of wisdom you're willing to
pass our way.

You can fax, email, or write me directly to let me know what you did or didn't like about
this book—as well as what we can do to make our books stronger.

Please note that I cannot help you with technical problems related to the topic of this
book, and that due to the high volume of mail I receive, I might not be able to reply to
every message.

When you write, please be sure to include this book's title and author as well as your
name and phone or fax number. I will carefully review your comments and share them
with the author and editors who worked on the book.

Fax: 317-581-4770

E-mail: [email protected]

Mail: Michael Stephens


Associate Publisher
Sams Publishing
201 West 103rd Street
Indianapolis, IN 46290 USA

Linux and Java: The Choice of a New


Millennium
Welcome to Java. Welcome to Linux. Welcome to the five-year revolution.

Five years ago, as Microsoft Windows 95 swept the world, Linux and Java were tiny blips
on the radar. In 1995, The term "Open Source" had not yet been coined, Linux was an
underground movement, and Java was struggling to prove itself a working technology.

What a difference five years makes!

In the past few years of explosive Internet growth, both Linux and Java have assumed
crucial roles in advancing network technologies and shaping the Web. Both have had to
mature quickly, and, with the recent releases of the Linux 2.2 kernel and the Java 2
Platform, both demand to be taken seriously as technologies and as businesses.

Which brings us to this book.

-7-
Linux and Java go together like, well… cream and coffee. Linux offers a powerful, stable,
efficient operating system; Java offers a powerful and portable applications platform of
huge and growing popularity. You've probably already used the two together—if you've
ever run Netscape Navigator on Linux. But there is much more to Java than applets and
browsers. This book will help you take the next step: to the world of Java applications,
Java development, and Java Web services.

Who Is This Book's Intended Audience?


If you need to use Java and Linux together, this book is for you. The book has a strong
focus on development tools and techniques, but we also cover topics of use to
nondevelopers (for example, Java installation and configuration) and administrators (for
example, Java Web services).

What Do You Need to Know Prior to Reading This Book?


Some previous exposure to both Java and Linux will be helpful, although we do include
introductions to both technologies. This book does not try to teach you Java or Linux (many
other fine books already do so)—it focuses on how you can use the two together.

What Will You Learn from This Book?


This book will teach you how to install and use a Java environment under Linux, how to
develop Java under Linux, and how to deploy your Java applications to Linux and other
platforms.

What Software Will You Need?


You will need a Linux distribution and a Java Software Development Kit—both are
available for free online. You can also buy reasonably priced Linux distributions on CD-
ROM. This book will tell you how to get all the software you need.

How This Book Is Organized


This book is organized into 15 parts, first introducing the technologies and then covering
installation, configuration, development, and deployment of Java on Linux.

The parts of the book are as follows:

• Part I: A Brief Introduction to Java—If you're new to Java, this part takes you on a
brief tour of the language and the environment.

• Part II: A Brief Introduction to Linux—If you're new to Linux, this part gives you a
brief introduction to the operating system and helps you get started setting up a Linux
system.

• Part III: Setting Up for Java Development and Deployment on Linux—This part
describes the pieces you need to enable Java deployment and development in your
Linux environment.

• Part IV: The Blackdown Port: A Sun Java SDK for Linux—The Blackdown
organization is the group responsible for porting Sun's Java software to Linux. This
part of the book describes how to obtain and install Java runtime and development
software from Blackdown.

• Part V: Tools in the Blackdown JSDK—The Java Software Development Kit (JSDK)
from Blackdown includes all the pieces you need to develop, test, and run Java. Here
we describe the tools and how to use them.

-8-
• Part VI: Additional Java Runtime Environments—The Sun software distributed by
Blackdown is not the last word in running Java on Linux. This part describes
alternative Java environments you can use under Linux.

• Part VII: Additional Java Runtime Components—This part of the book describes
additional components to make your Java environment faster, better, and more
capable.

• Part VIII: Compilers and Debuggers—You have many Java development tool
choices beyond the SDK. Here we present some alternative compilers and debuggers
you can use.

• Part IX: IDEs, GUI Builders, and RAD Tools—This part explores advanced
development tools—integrated development environments, user interface builders,
and rapid application development tools—available for use on Linux. One such tool,
Inprise JBuilder, is bundled on the accompanying CD-ROM.

• Part X: Miscellaneous Development Tools—Here we explore some tools that can


assist your Java development efforts under Linux.

• Part XI: Java Application Distribution—This part of the book helps you distribute
your Java applications to the rest of the world, including users on other operating
systems.

• Part XII: Linux Platform Issues—This part discusses issues specific to using Java on
the Linux platform, such as accessing native platform capabilities and dealing with the
X Window System.

• Part XIII: Java Performance—This part explores Java performance: why it's slow,
why it's improving, and how you can tune your own applications for better
performance.

• Part XIV: Java and Linux on Servers—Java and Linux both have important roles on
three-tier applications servers and Web servers. This part of the book discusses using
Linux and Java for server applications.

• Part XV: Appendixes—Here you'll find an index of programs provided in the book,
some code listings, and some pointers to additional resources.

Visit Our Web Site


This book has its own Web site: http://www.javalinux.net. Please visit the site for
the latest updates, errata, and downloads.

Conventions Used in This Book


This section describes the important typographic, terminology, and command
conventions used in this book.

Typographic Conventions Used in This Book


The following typographic conventions are used in this book:

• Code lines, commands, statements, variables, and any text you type or see onscreen
appears in a mono typeface. Bold italic mono typeface is often used to represent
the user's input.

-9-
• Command syntax descriptions use the following notation to describe commands and
arguments:

– monospaced text—This represents the literal text of a command or option.

– <monospaced italics in angle-brackets>—Angle-brackets and italic text


represent placeholders in a command description. These placeholders are replaced
by commands or options described in the text.

– [<optional arguments>]—Brackets surround optional arguments. A vertical


stroke may separate multiple choices for an optional argument.

– {on¦off}—Curly braces surround a required multiple-choice argument, with


choices separated by a vertical stroke.

For example, a syntax description like this

java [-green¦-native] [<options>] <class>

could result in the command

java –green –classpath . MyClass

• Long listings of code or output are printed with line numbers to aid in reading. If a line
is too wide to fit on the page, the remainder appears in the following line without a line
number.

• The book also contains Subtleties sidebars that explore a topic in more detail. The
information here may not be of immediate use but is helpful in better understanding
the topic or solving difficult problems.

Naming Conventions Used in This Book


The naming of Sun Java releases has been a matter of some confusion over the years.
This book adopts a convention consistent with Sun's most recent practices:

• JDK—A JDK is a Java technology release, such as JDK1.0, JDK1.1, and JDK1.2. (Its
original meaning was "Java Development Kit," but common usage has broadened it to
mean an entire technology release. This is discussed in more detail in Chapter 10,
"Java Components for Linux," in the section on "A Glossary of Sun Java
Terminology.")

• SDK—An SDK is a Software Development Kit. Every Java technology release is


accompanied by an SDK that includes tools, such as compilers and debuggers, for
Java development.

• JRE—A JRE is a Java Runtime Environment. This is a subset of the SDK targeted at
deployment platforms. It contains everything needed to run Java programs but no
development tools.

Command Shell Conventions in This Book


In UNIX and Linux environments, users have a choice of command shells—interactive
command interpreters—to use for running commands in terminal windows.

This book will assume the use of bash (the Bourne-Again SHell), which is the most
popular Linux command shell. Command input lines will be shown with this prompt:

- 10 -
bash$

So a user interaction with bash could look like this:

bash$ echo Hello World


Hello World
bash$

When an input line is too long in a Linux command shell, you can end it with the
backslash character and continue it on the next line:

bash$ echo The quick brown fox jumps over the lazy \
dog
The quick brown fox jumps over the lazy dog
bash$

For most interactions discussed in this book, the choice of command shell has little effect
on how commands are entered. But there are two important exceptions.

Setting Environment Variables


Different command shells use different commands for setting environment variables.
When this book specifies setting of variables, it will use the bash notation:

bash$ FOO=bar
bash$ export FOO

or the shorter form:

bash$ export FOO=bar

or, occasionally, the form used to set the variable for the duration of a single command:

bash$ FOO=bar <command>. . .

For users who prefer the popular csh (C-shell) or tcsh (a csh clone), you will need to
perform your own translation to the csh-style notation:

setenv FOO bar

Environment Initialization File


The name of the initialization file is another important command shell difference.

When you start a new login session running bash, it reads a file called
~/.bash_profile (that's .bash_profile in your home directory) for any user-
specific setup of your environment. This book sometimes instructs you to add commands
to that file for setting environment variables.

If you are a csh or tcsh user, you will need to translate these instructions. The
initialization file it reads is called ~/.login (.login in your home directory)—this is
where you will need to add the corresponding setenv commands.

- 11 -
Part I: A Brief Introduction to Java
Chapter List

Chapter What Is Java?


1:

Chapter Moving from C++ to Java


2:

Chapter A Look at the Java Core Classes


3:

Chapter Additional Sun Java Class Library Specs


4:

Part Overview
The first part of the book provides a brief introduction to Java. If you're a Linux user or
developer coming to Java for the first time, you may find the Java concept a bit
bewildering because Java is a lot of things: a language, an architecture, an applications
platform, and more.

So we begin with a look at what Java really is, where and how it is used, what it offers to
programmers, and what sort of applications capabilities it provides.

Chapter 1: What Is Java?


Overview
This chapter gives you the 10-minute tour of Java. If you're already experienced with
Java, you might want to skip ahead. On the other hand, if you're new here, you might find
that Java is not exactly what you thought it was. It's not just a language, and it's not just
for Web browsers.

So what exactly is Java? It's a language. It's a machine architecture. It's a loading model.
It's a file format. It's an applications environment (several different applications
environments, actually). It's a specification. And it's an implementation.

Java began life as a failed Sun research project called Oak, targeted at embedded
operation in appliances. In 1995, Sun repackaged Oak as a portable "Internet programming
language" and positioned it initially as a way to run programs in Web browsers. The result
was something of a misfire: Web applets were not a huge success, and even today they
occupy a largely specialized niche. But Java displayed usefulness in other areas, and
interest in Java for different tasks—particularly Web services and enterprise connectivity—
skyrocketed. Java has since settled into a number of important application areas (we
explore more below), including, at long last, appliances!

The Many Faces of Java


Let's dissect Java in a bit more detail…

The Java Language

- 12 -
By the time Sun announced Java in 1995, C++ and object-oriented programming had
been around for years. C++ had grown, in episodic spurts, from a preprocessor into a full-
featured compiled language. It had become the language of choice for projects of all
scales, and it had been through several stages of standardization—culminating in the
acceptance of the ANSI C++ standard in 1998.

C++ had also, along the way, picked up considerable baggage. It had a substantial
number of non-object-oriented artifacts, and it had become a difficult language to write
compilers for. It was also difficult to achieve complete portability: even the excellent ANSI
standardization did not completely shield developers from platform-specific language
porting headaches.

One of Java's goals was to fix what was wrong with C++, with a special focus on the
error-prone aspects of C++ development—those that tend to take up too much
debugging time. In this it has certainly succeeded: Java developers (especially C++
converts) find the language well-suited for rapid prototyping and development. Java's
remedies include:

• Strengthening the object orientation and eliminating non-object-oriented features (for


example, macros, globals)

• Eliminating the error-prone direct manipulation of memory pointers and the confusion
of referencing and dereferencing

• Getting the developer out of the messy memory management business

• Adding type safety

• Performing runtime checking for such common problems as illegal typecasting, bad
array subscripts, and null object references

• Supporting multithreaded programming directly in the language

• Improving exception handling

A detailed language specification is available, both in printed form and from Sun's Web
site (http://java.sun.com). Like most specs, it is better as a reference work than a
learning tool. For actually learning the language, a good place to start would be Java
Unleashed (Sams).

Chapter 2, "Moving from C++ to Java," uses some programming examples to take a
closer look at the differences between Java and C++. Despite the differences, Java looks
much like C++, and experience suggests that C++ programmers can pick it up quickly
and easily. So although this book is not in the business of teaching the language, the
introduction and the examples should be enough to get you well past the "Hello World"
stage.

The Java Machine Architecture


The Java specification describes not only the high-level language but also the low-level
machine and instruction set it runs on: a concurrent, abstract stack machine with an
architecture and a small bytecode instruction set closely tied to the language (see Figure
1.1). This is roughly equivalent to dictating the CPU on which a language can be used,
although a better analog is the P-code machine that was used in the development of
UCSD Pascal some 20 years back.

- 13 -
Figure 1.1: Java defines a low-level architecture and instruction set closely
aligned with the high-level language.

Implementation of the architecture—as, for example, a silicon Java chip or as a virtual


machine—is left as an exercise for individual vendors. (This has turned out to be a
challenge to the acceptance of Java, but virtual machines are now available for Linux and
many other environments.)

In addition to describing an execution engine, the spec describes certain machine


behaviors: startup, shutdown, and, most interestingly, loading.

The Java Loading Model


The Java loading model is, ultimately, what makes Java unique. Loading of Java
modules (or classes, to be more correct) happens dynamically during program execution.
This is a radical change for generations of programmers accustomed to the compile-link-
load-run cycle for building and running programs and is resulting in new approaches to
structuring application functionality.

The loading of Java classes consists of several steps (see Figure 1.2):

1. Reading the bits

2. Verifying that the bits describe a well-structured class containing well-structured Java
code

3. Building a global class structure

4. Resolving references

5. Controlling access—allowing an application or environment to decide access rules for


class loading (such as restriction to trusted sources)

Figure 1.2: The Java class loader builds the environment during application
execution.

Loading of classes happens as needed, at any time during program execution—either


when a class is first referenced or when the application explicitly requests that a class be
loaded. The class-loading and security mechanisms are themselves classes and can be

- 14 -
modified by subclassing: Developers can define new sources of Java functionality not
envisioned by Java's creators.

The concept of runtime loading of functionality is certainly not new. We see it routinely in
dynamically loaded libraries, object models (CORBA, COM, and so on), and the plug-in
capability of many products. What is new is the full integration of class loading with the
language and the environment: it's never before been this easy, flexible, or extensible.
Allowing class loading from arbitrary sources (local disk, the Web, networked devices, a
dynamic code generator, and so on) is a notable advance in object-oriented
programming: it treats executable code objects with the same facility previously reserved
for data objects.

The loading model, combined with the portability of the code itself, gives Java bragging
rights as an "Internet programming language."

The Java Class File Format


Just as Java defines a portable instruction set, it defines a platform-neutral package for
Java code: the class file. Class files are usually generated by a Java compiler (they are
the Java analog of .o object files), after which they are ready to run (recall that linking
happens at runtime). Class files are typically found sitting on file systems or bundled into
archives (zip files, or the closely related Java archive jar files), where Java's default
class-loading mechanism expects to find them with the filename suffix .class. By
subclassing the class loader, as discussed previously, applications can introduce a class
file from any source.

The Java Applications Environment


As any UNIX/Linux programmer knows, modern applications run in a rich environment
provided by libraries (system, GUI, utility, and so on) and subsystems (X, printing, and so
on). Java, although not an operating system (OS), is substantially in the OS business: It
must provide a portable applications environment for everything from basic I/O services
to string manipulation to GUIs to networking. Java has undergone three major releases,
during which the applications environment has grown from minimal to substantial:

• JDK1.0—Sun's initial release, heavily hyped but not ready for prime time. A basic
applications environment with a basic GUI component (AWT, the Abstract Windowing
Toolkit) built on top of native platform GUI mechanisms.

• JDK1.1—A substantial improvement, introducing basic printing support, a better event


model, the JavaBeans component model, I18N, reflection, remote method invocation,
a security framework, and database connectivity. The latter three areas represent
Java's move into distributed enterprise applications.

• JDK1.2 (officially The Java 2 Platform, version 1.2)—Many consider this the first
ready-for-prime-time Java. It is huge but useful, introducing security enhancements, a
robust 2D graphics imaging model, the JFC Swing GUI toolkit (a native Java look and
feel), an accessibility API, drag-and-drop support, the collections classes, improved
persistence support, reference objects, an audio API, CORBA support, and more.

The language and architecture have also evolved with each release (nested classes, for
example, appeared in version 1.1), but the environment has changed most dramatically.

When we speak of JDK1.1 or JDK1.2, we are referring to a complete application


environment—Java Virtual Machine (JVM) + class libraries—that is used for two distinct
purposes:

• Running applications (Figure 1.3)—Applications are standalone programs with the


same rights and responsibilities as programs in any other language. Like C++
programs, standalone Java programs begin with a call to main() and end, typically,

- 15 -
with a call to exit(). A standalone program is usually run by invoking a JVM and
specifying a class file to execute.

Figure 1.3: Java applications run in a platform-neutral environment within the


host environment.

• Running applets (Figure 1.4)—Applets run in browsers, embedded in Web pages,


typically under the control of a Java Runtime Environment (JRE) built into the browser.
Applets differ in three major respects from applications:

Figure 1.4: Java applets run in a platform-neutral environment provided by a


browser.

• The applet environment contains a restrictive security manager that prevents applets
from affecting the world outside the browser (such as the local file system) and
constrains the behavior of class loading and networking.

• Graphics happens to windows controlled by the browser—typically embedded in a


Web page, although browsers can launch top-level applet windows.

• Applets have a different life cycle from applications, described in terms of when they
are initially loaded, when they are started and stopped by the browser due to page
visibility, and when they are finally unloaded from the browser. There is no main() in
applets.

Applets are typically run when a browser reads a page containing the HTML tags to load
and execute a Java class.

Differences aside, both applets and applications expect a full JRE. So a browser
supporting JDK1.2 (as of this writing, neither major browser does) would include the full,
gigantic JDK1.2 environment—Swing toolkit and all.

Java does define other, simpler environments for use in more constrained applications:

• PersonalJava—A subset of JDK1.1 for personal devices such as Portable Digital


Assistants.

- 16 -
• EmbeddedJava—A subset of JDK1.1 for use in embedded controllers, with extensions
targeted at real-time environments. EmbeddedJava is a political hot potato at the
moment: A number of vendors with deep experience in real-time systems were so
dissatisfied with Sun's EmbeddedJava work that they formed the J-Consortium in early
1999 to work toward better, vendor-neutral real-time Java extensions.

• JavaCard—A Java environment for use in smart cards, "credit cards with brains,"
designed to support the application and transaction requirements of that market.

• JavaTV—A Java environment for use with television-enabled applications such as


interactive programming and video-on-demand.

• JavaPhone—A set of API extensions, on top of PersonalJava or EmbeddedJava, for


development of telephony applications.

In mid-1999, Sun announced the Java 2 Platform Micro Edition, a unification targeted at
subsuming these technologies.

We examine the core JRE classes in more detail in Chapter 3, "A Look at the Java Core
Classes."

The Java Specification and Implementation


In the preceding sections, we have repeatedly mentioned specifications: Java is, first and
foremost, a specification. The complete specs for the language, the class file format, the
virtual machine, and the runtime environment are available from Sun—in printed form
from a bookstore, or in electronic form online (no charge; http://java.sun.com).

Given the Java specification, it is possible for anyone to create any part of Java—a
compiler, a VM, an SDK—without any encumbrances to Sun. Later, you learn of some
"cleanroom" Java pieces, built entirely from specs, available on Linux.

Sun has also created a reference implementation of everything in the spec: JVM, core
libraries, and a development kit containing a full complement of tools. Sun ships two
commercial implementations, for Solaris and Windows NT, that were created from the
reference implementation. It also licenses the reference implementation to other vendors,
which is the basis for commercial Java ports on such platforms as HP-UX, AIX, Ultrix,
and others. The reference implementation is also the basis for the Blackdown SDK for
Linux, which gets extensive coverage beginning in Chapter 13, "Blackdown: The Official
Linux Port."

Use of the reference implementation comes at a price: The source is available for no
charge, but any products built from it are encumbered by licensing obligations to Sun. The
licensing terms are reasonably generous to anyone building a noncommercial
implementation; all others pay fees, resulting in an important revenue stream for Sun.

Other Java Technologies


Sun has many other focused Java components, outside the core platform, in various
stages of specification and implementation (see Chapter 4, "Additional Sun Java Class
Library Specs," for more details). Among them:

• Java3D—Support for 3D imaging

• Java Media Framework—Multimedia support

• Java Servlets—Java on Web servers

- 17 -
• Java Cryptography Extensions—A framework for private- and public-key cryptography

• JavaHelp—A full-featured help system

• Jini—A framework for creating communities of "smart" devices, including automatic


network configuration and resource discovery

• JavaSpeech—An API for speech recognition and synthesis

• Java 2 Enterprise Edition—A collection of technologies—directory, database, email,


messaging, transaction, and so on—targeted at deployment in the enterprise
environment

Where Is Java Used?


Some settings in which Java has found a home (beginning with the two traditional ones)
are as follows:

• Standalone Java applications hosted by a JRE under many different operating


systems: Linux, NT, MacOS, all important flavors of UNIX, IBM's mainframe OSs, and
so on.

• Applet JRE environments provided by Netscape Navigator and Microsoft Internet


Explorer Web browsers.

• Web servers, for programmatic generation of Web content.

• Application servers, integrating the activities of enterprise applications, databases, and


Web activities.

• Java PCs—Sun's JavaOS is an operating system, intended for use in network


computers and appliances, in which Java classes are the native application format.

• Inside Database Management Systems (DBMSs) such as Oracle and Sybase,


supporting stored procedures for smart database queries.

• Television set-top boxes, running JavaTV.

• Smart cards—a complete Java Virtual Machine plus the card-holder's data can reside
in a chip on a small plastic card.

• Embedded controllers in consumer and industrial devices: printers, cameras, robots,


and so on.

• Jewelry—rings, wristwatches, money clips, and so on with built-in JVMs and a


waterproof hardware interface. They are used for identification, e-commerce, and
cryptography (yes, Java-based secret decoder rings!).

In later chapters, we explore how some of these environments are being deployed in Linux.

What Can't You Do in Java?


Java is, in many ways, a computer scientist's dream. It brings together many of the most
interesting technologies of the past 20 years, from garbage collection to architecture-
neutral code to on-the-fly optimization to runtime validation to OOP. Many of these
technologies have not become mainstream because, in the real world, they're just too
slow.

- 18 -
That is also Java's problem: it's slow. We examine performance issues (and what to do
about them) in more detail later. The performance story undoubtedly will improve, but
there is good reason to doubt that Java will ever challenge compiled native applications
in terms of speed. Among the problems Java cannot handle today:

• Performance-critical problems—These still require native applications or, at the very


least, native-code components in Java applications.

• Large problems—Problems with large memory or I/O requirements require the


application to take an active role in managing memory or I/O—application tuning
makes the difference between usable and unusable software in such demanding areas
as simulations and DBMSs. Java is not a supportive environment for such problems.

• Platform-specific problems—Java takes great pains to achieve platform-


independence, to the point of denying you many capabilities you take for granted in
native languages or even in many platform-independent scripting languages. You
cannot, without writing a native code component, detect or create a symbolic link,
implement an X Window manager, read UNIX environment variables, identify the
owner of a file, change tty settings, and so on. (We explore platform issues, including
solutions to some of these problems, in Chapters 55, "JNI: Mixing Java and Native
Code on Linux," and 56, "X Window System Tips and Tricks.")

• GUIs—Of course Java does GUIs—Swing is a first-rate toolkit. But GUI performance
needs a great deal of attention if Java is to be a serious