Sunday, October 26, 2008
Debugging Java Code in the CVM
separate debug proxy of the type used by KVM. However, before you can start debugging,
you need to do two things:
1. Build the CVM with the CVM_DEBUG and CVM_JVMDI options to the make
command set to true.
2. Build the library libjdwp, which contains the native code that implements the Java
Debug Wire Protocol (JDWP). This protocol allows debuggers to connect to the VM
over a socket or using shared memory.
You can build libjdwp using the following commands:
cd $CDC/ext/jpda/build/linux
make
This creates the library and writes it to the file $CDC/jdk_build/linux/lib/i386/libjdwp.so.
Starting CVM for debugging requires quite a long command line:
cvm -Xdebug -Xrunjdwp:transport=dt_socket,server=y,address=5000
-Xbootclasspath:$CDC/build/linux/lib/foundation.jar -Dsun.boot.library.
path=$CDC/jdk_build/linux/lib/i386 -Djava.class.path=$EXAMPLES/src ora.
ch7.CVMProperties
The options used here are as follows:
-Xdebug
Starts the VM in debug mode. When this option is used, the VM suspends operation
before entering the main( ) method of the initial application class.
-Xrunjdwp
Tells the VM to use JDWP for debugging. This option requires several parameters,
separated from it by a colon and from each other by commas, that specify how the
debugger will connect to the VM. In this case, the parameters supplied are as follows:
transport=dt_socket
Specifies that the debugger will connect over a socket.
server=y
Tells JDWP to take on the server role. The debugger itself acts as the client.
address=5000
Specifies the port number that the server should use to listen for a connection from the
debugger client.
-Xbootclasspath
Specifies the location of VM's boot classes, in this case the set of core and Foundation
Profile classes that have not been prelinked into the VM.
-Dsun.boot.library.path
Gives the directory in which the JWDP implementation library (libjdwp.so for Linux)
can be found.
-Djava.class.path
Specifies the locations to be searched for application classes.
Once the CVM has started, it will suspend and wait for a debugger to connect to it on the port
specified in the -Xrunjdwp argument. If you have an IDE that supports remote JPDA
debugging (such as Forte for Java), you can use it to perform source- level debugging. Alternatively, you can use the command-line tool jdb, which is part of the J2SE SDK. To connect using jdb, you need to specify the socket address on which the VM is listening and the location at which the source code for the application's classes can be found:
jdb -attach localhost:5000 -sourcepath $EXAMPLES/src
Here, jdb and the CVM are assumed to be on the same machine, but this need not be the case.
Following connection, you need to use the step command to force the VM to enter the
main( ) method. From here, you can use jdb commands to set breakpoints, list the source
code around the line currently being executed, inspect and modify objects and fields, and so
on.
By default, when you use the -Xdebug argument, the JVMDI support in the VM starts at the
same time as the VM itself and suspends execution until a debugger connects to it. However,
you can choose to have JVMDI defer its initialization until an exception of a named type or an
uncaught exception is thrown. The latter case is often the type of error that you would like to
use a debugger to investigate, but starting the VM in debug usually causes it to execute byte
codes more slowly. Using this feature, you can run the VM at full speed until the exception
occurs.
The options that control the point at which the debugging features initialize is part of the -
Xrunjdwp argument. The following command:
cvm -Xdebug -Xrunjdwp:transport=dt_
socket,server=y,address=5000,onuncaught=y -Xbootclasspath:$CDC/build/
linux/lib/foundation.jar -Dsun.boot.library.path=$CDC/jdk_build/linux/
lib/i386 -Djava.class.path=$EXAMPLES/src ora.ch7.CVMException
adds the onuncaught option with value y, which delays initialization of the JVMDI until an
uncaught exception occurs. The class ora.ch7.CVMException used here waits for 10
seconds, then deliberately causes a NullPointerException that it does not catch, at which
point the debug facilities initialize and the VM is suspended. You can now start jdb to analyze
the problem.
Alternatively, if you simply want to start debugging when a NullPointerException occurs,
use the onthrow option, which requires the class name of the exception to wait for:
cvm -Xdebug -Xrunjdwp:transport=dt_
socket,server=y,address=5000,onthrow=java.lang.NullPointerException
-Xbootclasspath:$CDC/build/linux/lib/foundation.jar -Dsun.boot.library.
path=$CDC/jdk_build/linux/lib/i386 -Djava.class.path=$EXAMPLES/src
ora.ch7.CVMException
Finally, you can use the launch option to cause a command to be executed when the VM
debug facilities initialize. This option requires the name of the command, which should be
either an absolute path or the name of an executable on your search path (i.e., included in the
PATH variable for Linux). When it is started, the program receives the transport name and
address used by the debugger as arguments -- that is, it is effectively run with arguments like
this:
name dt_socket 5000
One way to make use of this is to create a script that starts jdb when the condition that starts
the JVMDI support occurs, like this:
#!/bin/sh
jdb -attach localhost:$2 -sourcepath $EXAMPLES/src
If you put these lines into a file called startdbg.sh (in a directory included in your PATH
variable) and make it executable (using a command like chmod +x startdbg.sh), the
following command:
cvm -Xdebug -Xrunjdwp:transport=dt_
socket,server=y,address=5000,onthrow=java.lang.
NullPointerException,launch=startdbg.sh -Xbootclasspath:$CDC/build/
linux/lib/foundation.jar -Dsun.boot.library.path=$CDC/jdk_build/linux/
lib/i386 -Djava.class.path=$EXAMPLES/src ora.ch7.CVMException
runs the VM until a NullPointerException occurs, at which point it initializes the JVMDI
code, suspends bytecode execution, and runs your script. This results in jdb starting and
connecting to the VM, using the port number that is passed as the second argument to the
script.
Saturday, October 4, 2008
MIDP GUI Programming
User interface requirements for handheld devices are different from those for desktop computers. For example, the display size of handheld devices is smaller, and input devices do not always include pointing tools such as a mouse or pen input. For these reasons, you cannot follow the same user-interface programming guidelines for applications running on handheld devices that you can on desktop computers.
The CLDC itself does not define any GUI functionality. Instead, the official GUI classes for the J2ME are included in profiles such as the MIDP and are defined by the Java Community Process (JCP). You'll note that the GUI classes included in the MIDP are not based on the Abstract Window Toolkit (AWT).Click Here To Read More
Basic I/O
java.io
package.Click Here To Read More
Using and Programming Generics in J2SE 5.0
int
to a collection; since you cannot have collections of primitive data types you must convert the int
to the corresponding reference type (i.e. Integer
) before storing it in the collection. Now, when the element is extracted from the collection an Object is returned that must be cast to an Integer
in order to ensure type safety. All this makes Java programs unnecessarily hard to read and maintain, and are more likely to fail with runtime errors. If the compiler could keep track of the element type, you do not need to keep track of what collections you have and the need for casting would be eliminated. This would make programs easier to read and maintain, and less likely to fail at runtime. J2SE 5.0 has added a new core language feature known as generics (also known as parameterized types), that provides compile-time type safety for collections and eliminate the drudgery of casting. The effort of adding generics to Java is led by Sun Microsystems as JSR 14 under the Java Community Process (JCP).
Generics are one of the most frequently requested language extensions to Java, and they have been finally added in J2SE 5.0. This article provides an introduction to programming with generics.
The Need for Generics
The motivation for adding generics to the Java programming language stems from the lack of information about a collection's element type, the need for developers to keep track of what type of elements collections contain, and the need for casts all over the place. Using generics, a collection is no longer treated as a list of
Object
references, but you would be able to differentiate between a collection of references to Integer
s and collection of references to Byte
s. A collection with a generic type has a type parameter that specifies the element type to be stored in the collection.Click Here To Read More
THE CONNECTED DEVICE CONFIGURATION AND THE FOUNDATION PROFILE
Much of what's been written about Java 2 Platform, Micro Edition (J2ME) talks about the Connected Limited Device Configuration, or CLDC for short. The CLDC defines an extremely small subset of the Java Platform for very limited devices -- devices, like cellular telephones, that do not have enough memory or enough processing power to handle a full-blown Java implementation. There is, however, another configuration available that is midway between the CLDC and a full Java 2 Platform, Standard Edition (J2SE) implementation: the Connected Device Profile, or CDC for short.
Click Here To Read More
Friday, October 3, 2008
Return-Type-Based Method Overloading in Java
int doXyz(int x)
and double doXyz(int x)
in the same class. And indeed, the Java compiler duly rejects any such attempt. But recently I discovered a way to do this, which I wish to share with all. Along the way, we will also explore some rudiments of Java bytecode programmingClick Here To Read More
An Introduction to the Lightweight User Interface Toolkit (LWUIT)
Non-uniform look and feel is not the only reason why developers have been waiting for something better to turn up. The javax.microedition.lcdui package does not support components and capabilities that can fully satisfy present-day user expectations.
It is in this context that the arrival of Lightweight User Interface Toolkit (LWUIT) is so exciting. LWUIT offers a wide range of widgets for building UIs. While some of these widgets are also available under lcdui, there are a number of new ones that enable application developers to design UIs that can come very close to their desktop counterparts in terms of visual sophistication. Even the components that are also offered by lcdui have been functionally enhanced. And LWUIT is not just about new components, either. The API supports a whole range of new functionalities, too -- theming, transitions, and more.
Java Media Framework Player API
Multimedia playback comes to Java! Learn how to start using audio and video in your applets and applications
What is the Java Media Framework?The JMF is a set of three new APIs being co-defined by the JMF Working Group members -- Sun, Silicon Graphics, and Intel. These APIs eventually will include Java Media Player, Capture, and Conferencing. The first to be delivered, the Player API provides a framework for implementors to build media players and provide them in a standard way on all Java platforms. The JMF specification is flexible enough to allow developers to extend players by adding their own nodes (such as images filters, audio reverb effects, and so on) or to use the standard players without making any additions.
Click Here To Read More
Painting in AWT and Swing
Both the AWT (abstract windowing toolkit) and Swing provide such a framework. But the APIs that implement it are not well understood by some developers -- a problem that has led to programs not performing as well as they could.
This article explains the AWT and Swing paint mechanisms in detail. Its purpose is to help developers write correct and efficient GUI painting code. While the article covers the general paint mechanism (where and when to render), it does not tell how to use Swing's graphics APIs to render a correct outputClick Here To Read More
Double Buffering and Page Flipping
Suppose you had to draw an entire picture on the screen, pixel by pixel or line by line. If you were to draw such a thing directly to the screen (using, say, Graphics.drawLine), you would probably notice with much disappointment that it takes a bit of time. You will probably even notice visible artifacts of how your picture is drawn. Rather than watching things being drawn in this fashion and at this pace, most programmers use a technique called double-buffering.
Click Here To Read More
Introduction to Java media programming
Learn the basics of Java-based multimedia with the Java Media and Communication APIs
Java as a versatile programming language has gained widespread acceptance in the two-plus years since its introduction. It is widely espoused as having the usual benefits with which we are all familiar: cross-platform portability, a fairly secure runtime environment, strong networking and connectivity APIs, and so on.However, no one could credibly argue that the Java platform as we know it (the 1.0 and 1.1 core platforms) is a multimedia power house. In fact, far from offering a robust set of multimedia APIs, Java as a platform still is adding a great many features and gaining acceptance. Media support is only now beginning to roll into the core platform (as part of the upcoming 1.2 release, which will include the Java 2D API and Java Sound engine).
These developments show promise for Java's media capabilities. In future installments of this column we'll be exploring the many aspects of this promise.
Image processing with Java 2D
Sophisticated image processing support comes to Java in the 2D API
Image processing is the art and science of manipulating digital images. It stands with one foot firmly in mathematics and the other in aesthetics, and is a critical component of graphical computer systems. If you've ever bothered with creating your own images for Web pages, you will no doubt appreciate the importance of Photoshop's image manipulation capabilities for cleaning up scans and clearing up less-than-optimal images.
If you did any image processing work in JDK 1.0 or 1.1, you probably remember that it was a little obtuse. The old model of image data producers and consumers is unwieldy for image processing. Before JDK 1.2, image processing involved MemoryImageSource
s, PixelGrabber
s, and other such arcana. Java 2D, however, provides a cleaner, easier to use model.
Saving bitmap files in Java
A tutorial -- including all the code you need to write a bitmap file from an image object
A tutorial on how to save images in 24-bit bitmap files and a code snip you can use to write a bitmap file from an image object.
Click Here To Read MoreBeginning J2ME: Building MIDlets
MIDP (Mobile Information Device Profile) applications are piquantly called MIDlets, a continuation of the naming theme begun by applets and servlets. Writing MIDlets is relatively easy for a moderately experienced Java programmer. After all, the programming language is still Java. Furthermore, many of the fundamental APIs from java.lang
and java.io
are basically the same in the MIDP as they are in J2SE. Learning the new APIs (in the javax.microedition
hierarchy) is not terribly difficult.
The actual development process, however, is a little more complicated for MIDlets than it is for J2SE applications. Beyond a basic compile-and-run cycle, MIDlets require some additional tweaking and packaging. The complete build cycle goes like this: edit, source code, compile, preverify, package, test or deploy.
To show how things work, and to give you a taste of MIDlet development, this article is dedicated to building and running a simple MIDlet. In this article, you'll get a feel for the big picture of MIDlet development.
How to break a String into tokens with the StringTokenizer class
In this article we'll demonstrate how to break Java String's into smaller components, called tokens. We'll begin by breaking a simple well-known sentence into words, and then we'll demonstrate how to use the same technique to work with a flat-file database.
Click Here To Read More
Random Numbers in Java
The best way to think of class Random is that its instances are random number generator objects -- objects that go around spitting out random numbers of various sorts in response to messages from their clients.
How to make a JAVA application - executable JAR archive
Create a batch file with the following content:
javac DiveLog.java
jar cvfm DiveLog.jar mymanifest DiveLog.class DiveLog$1.class DiveLog$2.class Welcome.class
Watch the line wrap: There are only 2 lines in the batch file, one starting with javac and the other with jar.
Run the batch file and it should compile the application and create DiveLog.jar, which can be clicked in order to run it.
You can also run the application from the command line by typing:
java -jar DiveLog.jarwhich does the same like clicking on the icon of the application, but you can see any output written by System.out.println("..."); or error messages.
Click Here To Read More
Debugging with the Eclipse Platform
Find out how to use the built-in debugging features in the Eclipse Platform for debugging software projects. Debugging is something programmers can't avoid. There are many ways to go about it, but it essentially comes down to finding the code responsible for a bug. For example, one of the most common errors in Linux® applications is known as a segmentation fault. This occurs when a program attempts to access memory not allocated to it and terminates with a segmentation violation. To fix this kind of error, you need to find the line of code that triggers the behavior. Once the line of code in question has been found, it is also useful to know the context in which the error occurs, and the associated values, variables, and methods. The use of a debugger makes finding this information quite simple.
Click Here To Read More
What Is Performance?
"More computing sins are committed in the name of efficiency (without necessarily achieving it) than for any other single reason-including blind stupidity."Before we can discuss how to improve performance, it's necessary to define what performance is. This isn't as simple as it sounds-people often mean very different things when they talk about performance. There are several aspects of performance, each of which contribute to the overall performance of an application.
Computers fascinate people with their ability to carry out tasks with blinding speed. When a computer, for whatever reason, doesn't perform a task quickly, users are disappointed. Developers often use the terms "speed" and "performance" interchangeably. However, to understand the different types of problems that can be encountered, all of the different aspects of performance must be considered:
These factors lay the foundation for a better understanding of the performance landscape. Some aspects of performance are primarily applicable to client-side systems, some to server-side systems, and some to both. Understanding how each factor can contribute to the performance characteristics of a system will help you analyze the performance of your own applications.
RAM Footprint
Before you can optimize your program's footprint, it's important to understand how memory is used. There are many common misconceptions about how memory is consumed by Java programs, and it is easy to put a lot of effort into footprint control for relatively small gains. By understanding the factors that contribute to footprint, you can make informed decisions when coding.
Using MediaTracker to help load images
Click Here To Read More
Java vs C in speed performance
Fiction :
Java is a hundred times slower than C, so you shouldn't ever use it for "serious" programming.
Fact :
The original Java Virtual Machines were slow, so slow that a comparable C application was about twenty times faster. The gap between C/C++ and Java is growing smaller though, thanks to better designed JVMs, and Just-In-Time (JIT) compilers that convert bytecode to native machine code at runtime.
Much of the cause for speed concerns is actually over applet loading - large applets take a long time to load initially. Thankfully, Java applications and servlets are not subject to such slow loading times.
Fiction :
Applets can read your hard-drive, and delete files
Fact :
Any attempt by an applet to access local files will throw a SecurityException. If uncaught, the applet will crash, but no file access will occur.
The only exception to this rule is for digitally signed applets, which may be granted additional privileges. Your browser will display a dialog box, asking you if you want to accept the identity of the applet author. Choose no if unsure, and you'll always be safe.
Thread Synchronization
Click Here To Read More
Inside the Java Virtual Machine
The Java virtual machine is called "virtual" because it is an abstract computer defined by a specification. To run a Java program, you need a concrete implementation of the abstract specification. This chapter describes primarily the abstract specification of the Java virtual machine. To illustrate the abstract definition of certain features, however, this chapter also discusses various ways in which those features could be implemented.
What is a Java Virtual Machine?
To understand the Java virtual machine you must first be aware that you may be talking about any of three different things when you say "Java virtual machine." You may be speaking of:
- the abstract specification,
- a concrete implementation, or
- a runtime instance.
Each Java application runs inside a runtime instance of some concrete implementation of the abstract specification of the Java virtual machine. In this book, the term "Java virtual machine" is used in all three of these senses. Where the intended sense is not clear from the context, one of the terms "specification," "implementation," or "instance" is added to the term "Java virtual machine".
Handling memory leaks in Java programs
Memory leaks in Java programs? Absolutely. Contrary to popular belief, memory management is still a consideration in Java programming. In this article, you'll learn what causes Java memory leaks and when these leaks should be of concern. You'll also get a quick hands-on lesson for tackling leaks in your own projects.
Click Here To Read More
MVC meets Swing
Explore the underpinnings of the JFC's Swing components
A good software user interface often finds its genesis in the user interfaces present in the physical world. Consider for a moment a simple button like one of the keys on the keyboard in front of you. With such a button there is a clean separation between the parts that compose the button's mechanism and the parts that compose its façade. The building block called a keyboard key is actually composed of two pieces. Once piece gives it its button-like behavior. The other piece is responsible for its appearance.This construction turns out to be a powerful design feature. It encourages reuse rather than redesign. Because your keyboard's keys were designed that way, it's possible to reuse the button mechanism design, and replace the key tops to create a new key rather than designing each key from scratch. This creates a substantial savings in design effort and time.
Not surprisingly, similar benefits occur when this technique is applied to software development. One commonly used implementation of this technique in software is the design pattern called Model/View/Controller (MVC).
That's all well and good, but you're probably wondering how this relates to the Swing user interface components in the Java Foundation Classes (JFC). Well, I'll tell you.
While the MVC design pattern is typically used for constructing entire user interfaces, the designers of the JFC used it as the basis for each individual Swing user interface component. Each user interface component (whether a table, button, or scrollbar) has a model, a view, and a controller. Furthermore, the model, view, and controller pieces can change, even while the component is in use. The result is a user interface toolkit of almost unmatched flexibility.
Let me show you how it works.
Click Here To Read MoreIntroduction to the AWT
A description of Java's user interface toolkit
The Java programming language class library provides a user interface toolkit called the Abstract Windowing Toolkit, or the AWT. The AWT is both powerful and flexible. Newcomers, however, often find that its power is veiled. The class and method descriptions found in the distributed documentation provide little guidance for the new programmer. Furthermore, the available examples often leave many important questions unanswered. Of course, newcomers should expect some difficulty. Effective graphical user interfaces are inherently challenging to design and implement, and the sometimes complicated interactions between classes in the AWT only make this task more complex. However, with proper guidance, the creation of a graphical user interface using the AWT is not only possible, but relatively straightforward.This article covers some of the philosophy behind the AWT and addresses the practical concern of how to create a simple user interface for an applet or application.
Java's garbage-collected heap
An introduction to the garbage-collected
heap of the Java virtual machine
Why garbage collection?
Garbage collection relieves programmers from the burden of freeing allocated memory. Knowing when to explicitly free allocated memory can be very tricky. Giving this job to the JVM has several advantages. First, it can make programmers more productive. When programming in non-garbage-collected languages the programmer can spend many late hours (or days or weeks) chasing down an elusive memory problem. When programming in Java the programmer can use that time more advantageously by getting ahead of schedule or simply going home to have a life.
A second advantage of garbage collection is that it helps ensure program integrity. Garbage collection is an important part of Java's security strategy. Java programmers are unable to accidentally (or purposely) crash the JVM by incorrectly freeing memory.
A potential disadvantage of a garbage-collected heap is that it adds an overhead that can affect program performance. The JVM has to keep track of which objects are being referenced by the executing program, and finalize and free unreferenced objects on the fly. This activity will likely require more CPU time than would have been required if the program explicitly freed unnecessary memory. In addition, programmers in a garbage-collected environment have less control over the scheduling of CPU time devoted to freeing objects that are no longer needed.
Fortunately, very good garbage collection algorithms have been developed, and adequate performance can be achieved for all but the most demanding of applications. Because Java's garbage collector runs in its own thread, it will, in most cases, run transparently alongside the execution of the program. Plus, if a programmer really wants to explicitly request a garbage collection at some point, System.gc()
or Runtime.gc()
can be invoked, which will fire off a garbage collection at that time.
The Java programmer must keep in mind that it is the garbage collector that runs finalizers on objects. Because it is not generally possible to predict exactly when unreferenced objects will be garbage collected, it is not possible to predict when object finalizers will be run. Java programmers, therefore, should avoid writing code for which program correctness depends upon the timely finalization of objects. For example, if a finalizer of an unreferenced object releases a resource that is needed again later by the program, the resource will not be made available until after the garbage collector has run the object finalizer. If the program needs the resource before the garbage collector has gotten around to finalizing the unreferenced object, the program is out of luck.
Click Here To Read MoreAnother interesting article on Garbage Collection