Thứ Hai, 23 tháng 1, 2012

Recent Java-Related Posts Worthy of Special Notice

In this blog post, I reference and summarize recent Java-related posts that I have found to be particularly interesting and well worth the time spent reading them.

JDK 8 and Unsigned Integer Arithmetic

Joe Darcy's post Unsigned Integer Arithmetic API now in JDK 8 states that "initial API support for unsigned integer arithmetic" has been pushed into Java 8. Darcy explains that this is implemented largely via static methods on classes java.lang.Integer and java.lang.Long.

Although Darcy's post is not very long, he manages to talk about the specific unsigned arithmetic functionality that is supported (conversion of Strings to unsigned integers, conversion of unsigned integers to Strings, comparing unsigned values, and calculation of unsigned division and remainder) as well as why it was decided to not implement new types such as UnsignedInt. A consequence of not implementing specific unsigned types is that it is easier to inadvertently mix signed and unsigned values and Darcy suggests some ideas built on naming conventions or new built-in annotations to address this concern.

Versions, Code Names, and Features of Java Releases

Speaking of new versions of Java, another Joe (Joseph Kulandai) started 2012 off with a nice post on Java Versions, Features and History. In this post, Kulandai lists the versions of Java in backwards chronological order (Java SE 7 listed first and JDK Version 1.0 at the bottom of the post). Under each major version of Java, Kulandai provides bullet lists of new features in that release and provides the code name of each release.

Java 8 Status Updates

Continuing the theme of Java 8 updates, another post of interest is Johannes Thönes's Java 8 Status Updates. This post looks at the status of "the two big new language features of the upcoming Java SE 8" (Project Lambda and Project Jigsaw).

Java 7 Concurrency

Niklas Schlimm has written two recent posts on using Java 7 concurrency features. He introduces "a flexible thread synchronization mechanism called Phaser" in the post Java 7: Understanding the Phaser and looks in detail at ThreadLocalRandom in the post Java 7: How to write really fast Java code.

OutOfMemoryError: Using Command-line Tools

Vladimir Šor's Solving OutOfMemoryError (part 5) - JDK Tools is, as its title suggests, the fifth in a series on Java memory issues available on that blog ("Solving OutOfMemoryError blog post series"). This post provides a brief summary description and usage information for three command-line tools bundled with the Oracle Java SDK (jps, jmap, and jhat).

The previous entries in this series are written by Nikita Salnikov-Tarnovski: Solving OutOfMemoryError (part 1) - story of a developer, Solving OutOfMemoryError (part 2)- why didn’t operations solve it?, Solving OutOfMemoryError (part 3) - where do you start?, and Solving OutOfMemoryError (part 4) - memory profilers.

Debugging the JVM

Attila Balazs's post Debugging the JVM provides interesting insight on something that we don't seem to have to do as often these days as in the earlier days of the JVM, but could be a very useful resource on the occasions this does occur. Balazs talks about "crashing the JVM itself" via null thread group name and then goes onto explain using gdb in Linux to debug the issue with the JVM.

Groovy Introduction

Alex's post provides an introduction to Groovy including coverage of XML with Groovy, regular expressions with Groovy, and SQL with Groovy.

A New Java Blog With Two JavaFX Posts

I've posted before on why more developers should write blogs. One of the reasons is the variety of opinions and ideas that are generated that way. With this in mind, I have been interested to read the first two posts of new blog Experiments with Java. Both of the blog's current posts have been written in January 2012 and are on JavaFX 2. The posts are Percent Width for TableColumn in JavaFX 2.x TableView and Sliding in JavaFX (It’s all about clipping).

Conclusion

There have been several good Java-related posts in recent weeks and a sample of them are highlighted in this post.

Thứ Hai, 16 tháng 1, 2012

Book Review: JavaFX 2.0: Introduction by Example

Although Oracle's changes to JavaFX at JavaOne 2010 and JavaOne 2011 have converted me from a skeptic to a believer when it comes to JavaFX, the shift in JavaFX vision has not been without its downsides. In particular, the JavaFX book market has been tricky because nearly all available JavaFX books have been about version 1.x. In this post, I review the only book that I'm aware of at time of this writing that is completely focused on JavaFX 2.0: Carl Dea's JavaFX 2.0: Introduction by Example.

I'll start my review by stating the most important observation about JavaFX 2.0: Introduction by Example: it provided me exactly what I was looking for exactly when I needed it. There are some attributes of the book that might be considered negative by some readers that I felt were positives in my use of the book. I'll attempt in this post to articulate the finer points of these attributes so that prospective readers can make up their own minds.

JavaFX 2.0 Introduction by Example does exactly what the title implies: it introduces JavaFX 2.0 via numerous and varied examples. This code-heavy book is roughly similar to a "recipes" or "cookbook" with individual item covered (AKA a "recipe" in a recipes or cookbook) featuring subsections on the problem to be solved, the solution or solutions to that problem, and how those solutions work. Like the best recipes-oriented or cookbook-oriented software development books, this one is constructed so that Chapter 1 ("JavaFX Fundamentals") covers some of the basics of JavaFX early on. In other words, the reader is not dropped into JavaFX without first getting some examples of how to write and deploy basic "Hello World" style JavaFX applications.

Although JavaFX 2.0: Introduction by Example does provide introductory examples early on, I really appreciated the author not spending significant time discussing esoteric features of the language or delving into the history of JavaFX in tedious detail or providing pages worth of explanation on why JavaFX is the greatest thing since sliced bread. I'm usually in a hurry and I have come to resent books wasting my time on such things and this book doesn't do that. In this case, I was already familiar with these aspects of JavaFX (at least its history and why I might be interested in learning more about it), so I was especially appreciative of Dea not wasting paper and my time on that subject. In the book's concise "Introduction," Dea covers in a page and a half some advantages of JavaFX and "some history" of JavaFX along with a simple table articulating features of each release of JavaFX. It's a thing of beauty to be able to read all of this in less than two pages and in the introduction!

Dea covers some more background on JavaFX in the first chapter, but again limits that discussion to a single page. This page is more detailed than the introductory section and is a nice, brief segue into the technical meat of the book. This first page also contains the sentences that I think best sum up the value of this book:

Although this book doesn't go through an exhaustive study of all of JavaFX 2.0's capabilities, you will find common use cases that can help you build richer applications. Hopefully, these recipes can lead you in the right direction by providing practical and real-world examples.

This is exactly what JavaFX 2.0: Introduction by Example has done for me. It has provided me with a fast start into the world of JavaFX. Although I have since used several aspects of JavaFX not covered in this book, the book gave me the start that I needed and I was able to use JavaFX documentation for the areas not covered in this book.

JavaFX 2.0: Introduction by Example gets to the point quickly. Besides common things like the very brief introduction and the index, the book contains four chapters (32 "recipes") spanning 174 pages of text, images, and code. Dea doesn't even waste time with a conclusion, but ends the book with "recipe" 4.5 ("Displaying Content from the Database"). Although some readers may need a conclusion to bring closure to their reading experience, I usually little value in this for me as a reader and I didn't miss it here. I typically don't read these types of book cover-to-cover anyway (instead focusing on sections or recipes I am most interested in), so the conclusion is often unnecessary. Lack of a conclusion is another example of how Dea's book focuses most on what I want: the technical meat.

The four chapters in JavaFX 2.0: Introduction by Example are "JavaFX Fundamentals," "Graphics with JavaFX," "Media with JavaFX," and "JavaFX on the Web." The first chapter was most useful for quickly immersing myself into the basics of JavaFX and how to apply it. The examples in that chapter tend to be simple and easy to follow. The examples in the other three chapters tend to be more sophisticated because the functionality being covered tends to be more sophisticated. There are numerous lengthy code listings in the book. Although code listings may not be the easiest to read, I like to see actual code in any book on a language. Dea typically follows each code sample with descriptive text on any new feature shown in the code sample that had not been covered previously in the book. The code samples can be downloaded from Apress's site. The book also features numerous screen snapshots, which I consider a must for a book focused on user interfaces.

The concise and introductory approach of JavaFX 2.0: Introduction by Example that appealed to me may not appeal to everyone. This book, as advertised in the above cited quotation from the first chapter, is intended to be introductory (hence the title) and not to be exhaustive. Some topics that I have not seen covered in this book include subjects such as FXML, the JavaFX charting functionality, GroovyFX, and ScalaFX. Deployment is only lightly covered (and mostly via NetBeans), but Dea does reference Deploying JavaFX Applications for more details on JavaFX deployment. All of these areas, however, are fairly approachable given the JavaFX basics provided in this book. Dea recommends that readers reference forthcoming (mid-February 2012, Apress) Pro JavaFX 2.0 Platform for an "invaluable resource" that provides "further insight into JavaFX."

Although a small number of the items/recipes covered in JavaFX 2.0: Introduction by Example are based on and assume use of NetBeans, most examples in no way specific to any tool or IDE. Rather, most examples provide "raw" code that can be used in any IDE or favorite text editor. Indeed, many of the examples can be compiled with the javac compiler and executed with the java application launcher. I appreciated that in at least one NetBeans-oriented recipe, Dea took the page or two necessary to provide the code listing for code generated by NetBeans. This is invaluable for those who do not use NetBeans or who want to understand the code itself rather than simply understanding how to use NetBeans to generate the code.

JavaFX 2.0: Introduction by Example was exactly what I needed for an efficient and effective start to my investigation of JavaFX. It may not provide quite the level of soft introduction someone completely unfamiliar with JavaFX might want (especially if that person's basic Java skills are a little rusty) and it isn't an "exhaustive" JavaFX 2.0 reference either. It falls in between these extremes and seems to be a fast start example-based introduction to JavaFX for those who want to get into the core of JavaFX as quickly as possible. That's what I wanted when I purchased this book and I was happy to find out that's exactly what this book provides. It's completely JavaFX 2.x-oriented and there is no sign of deprecated JavaFX Script in any of the code examples.

Focus on JavaFX 2 FXML with NetBeans 7.1

In October 2011, I used the post Hello JavaFX 2.0: Introduction by NetBeans 7.1 beta to look at using NetBeans 7.1 beta to build a simple Hello, World style of JavaFX 2.0 application. In this post, I look at using NetBeans 7.1 (no longer in beta) to build a slightly more sophisticated JavaFX 2 application that makes heavy use of FXML.

Most of my posts on JavaFX 2 up to this point have emphasized the "pure Java" nature of JavaFX 2. The examples in these posts have been written in standard Java using JavaFX 2 APIs directly from the Java source code. These examples have also been built with the javac compiler and executed with the java application launcher. In this post, I take one of those examples [(Pure Java) JavaFX 2.0 Menus] and "port" it to use FXML for presentation layout.

For convenience, I include the entire Java listing for the "pure Java" implementation of the JavaFX 2 menus demonstration.

JavaFX 2.0 Menus Demonstration (Pure Java)

package dustin.examples;

import static java.lang.System.out;

import javafx.application.Application;
import javafx.beans.property.ReadOnlyDoubleProperty;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyCodeCombination;
import javafx.scene.input.KeyCombination;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

/**
* Example of creating menus in JavaFX.
*
* @author Dustin
*/
public class JavaFxMenus extends Application
{
/**
* Build menu bar with included menus for this demonstration.
*
* @param menuWidthProperty Width to be bound to menu bar width.
* @return Menu Bar with menus included.
*/
private MenuBar buildMenuBarWithMenus(final ReadOnlyDoubleProperty menuWidthProperty)
{
final MenuBar menuBar = new MenuBar();

// Prepare left-most 'File' drop-down menu
final Menu fileMenu = new Menu("File");
fileMenu.getItems().add(new MenuItem("New"));
fileMenu.getItems().add(new MenuItem("Open"));
fileMenu.getItems().add(new MenuItem("Save"));
fileMenu.getItems().add(new MenuItem("Save As"));
fileMenu.getItems().add(new SeparatorMenuItem());
fileMenu.getItems().add(new MenuItem("Exit"));
menuBar.getMenus().add(fileMenu);

// Prepare 'Examples' drop-down menu
final Menu examplesMenu = new Menu("JavaFX 2.0 Examples");
examplesMenu.getItems().add(new MenuItem("Text Example"));
examplesMenu.getItems().add(new MenuItem("Objects Example"));
examplesMenu.getItems().add(new MenuItem("Animation Example"));
menuBar.getMenus().add(examplesMenu);

// Prepare 'Help' drop-down menu
final Menu helpMenu = new Menu("Help");
final MenuItem searchMenuItem = new MenuItem("Search");
searchMenuItem.setDisable(true);
helpMenu.getItems().add(searchMenuItem);
final MenuItem onlineManualMenuItem = new MenuItem("Online Manual");
onlineManualMenuItem.setVisible(false);
helpMenu.getItems().add(onlineManualMenuItem);
helpMenu.getItems().add(new SeparatorMenuItem());
final MenuItem aboutMenuItem =
MenuItemBuilder.create()
.text("About")
.onAction(
new EventHandler<ActionEvent>()
{
@Override public void handle(ActionEvent e)
{
out.println("You clicked on About!");
}
})
.accelerator(
new KeyCodeCombination(
KeyCode.A, KeyCombination.CONTROL_DOWN))
.build();
helpMenu.getItems().add(aboutMenuItem);
menuBar.getMenus().add(helpMenu);

// bind width of menu bar to width of associated stage
menuBar.prefWidthProperty().bind(menuWidthProperty);

return menuBar;
}

/**
* Start of JavaFX application demonstrating menu support.
*
* @param stage Primary stage.
*/
@Override
public void start(final Stage stage)
{
stage.setTitle("Creating Menus with JavaFX 2.0");
final Group rootGroup = new Group();
final Scene scene = new Scene(rootGroup, 800, 400, Color.WHEAT);
final MenuBar menuBar = buildMenuBarWithMenus(stage.widthProperty());
rootGroup.getChildren().add(menuBar);
stage.setScene(scene);
stage.show();
}

/**
* Main executable function for running examples.
*
* @param arguments Command-line arguments: none expected.
*/
public static void main(final String[] arguments)
{
Application.launch(arguments);
}
}

Besides adding the ability to write JavaFX applications in "pure Java" as implemented in the last code listing, JavaFX 2 also provides FXML, an XML grammar for specifying a JavaFX application's layout. This approach is very similar to that provided by Flex's MXML, by OpenLaszlo's LZX, and by Mozilla's XUL. This approach works well with JavaFX's hierarchical Scene Graph.

The ported FXML code is shown next. It is easy to see the presentation structure in this XML.

JavaFx2Menus.fxml

<?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>

<VBox id="vbox" prefHeight="400" prefWidth="800"
xmlns:fx="http://javafx.com/fxml"
fx:controller="dustin.examples.MenuController">
<MenuBar fx:id="menuBar" onKeyPressed="#handleKeyInput">
<menus>
<Menu text="File">
<items>
<MenuItem text="New"/>
<MenuItem text="Open"/>
<MenuItem text="Save"/>
<MenuItem text="Save As"/>
<SeparatorMenuItem />
<MenuItem text="Exit"/>
</items>
</Menu>
<Menu text="JavaFX 2.0 Examples">
<items>
<MenuItem text="Text Example"/>
<MenuItem text="Objects Example"/>
<MenuItem text="Animation Example"/>
</items>
</Menu>
<Menu text="Help">
<items>
<MenuItem text="Search" disable="true"/>
<MenuItem text="Online Manual" visible="false"/>
<SeparatorMenuItem />
<MenuItem text="About" onAction="#handleAboutAction"/>
</items>
</Menu>
</menus>
</MenuBar>
</VBox>

The important portion of this simple FXML can be viewed on a single page within NetBeans 7.1 as shown in the next screen snapshot.

Besides the conciseness of the FXML and the aesthetically pleasing hierarchical presentation, the FXML also should look familiar to anyone who has worked with Flex, OpenLaszlo, or XUL. Most of the presentation structure is easily identified in the FXML document. This example includes an onAction handler that responds to the "About" menu item and there is an onKeyPressed action associated with the menu bar as well (I could not figure out a way to easily associate this handler with the menu item itself). Both of these actions reference names that start with the # symbol. The names following the # are names of methods on the controller class (defined by the fx:controller attribute of the VBox as the class named dustin.examples.MenuController). The source for this controller class is shown next.

MenuController.java

package dustin.examples;

import static java.lang.System.out;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.MenuBar;
import javafx.scene.input.InputEvent;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;

/**
* Controller class for JavaFX 2 Menus with FXML post and demonstration.
*
* @author Dustin
*/
public class MenuController implements Initializable
{
@FXML
private MenuBar menuBar;

/**
* Handle action related to "About" menu item.
*
* @param event Event on "About" menu item.
*/
@FXML
private void handleAboutAction(final ActionEvent event)
{
provideAboutFunctionality();
}

/**
* Handle action related to input (in this case specifically only responds to
* keyboard event CTRL-A).
*
* @param event Input event.
*/
@FXML
private void handleKeyInput(final InputEvent event)
{
if (event instanceof KeyEvent)
{
final KeyEvent keyEvent = (KeyEvent) event;
if (keyEvent.isControlDown() && keyEvent.getCode() == KeyCode.A)
{
provideAboutFunctionality();
}
}
}

/**
* Perform functionality associated with "About" menu selection or CTRL-A.
*/
private void provideAboutFunctionality()
{
out.println("You clicked on About!");
}

@Override
public void initialize(final URL url, final ResourceBundle rb)
{
menuBar.setFocusTraversable(true);
}
}

The above code from the controller class includes the two methods referenced as action handlers in the FXML with the # prefixes. These two methods are private and normally would not be visible to the FXML loader, but the use of the annotation @FXML gets around this problem. The menuBar attribute is also private but visible to the FXML loader thanks to its own @FXML annotation.

To get the application to respond to CTRL-A before any initial access of the menu bar, I found that I needed to have a reference to the menu bar in the controller and call setFocusTraversable(true) on that instance. Without doing that, the CTRL-A would only be responded to if I had first clicked on the menu bar once. The hook from the FXML to this attribute in the controller is the fx:id attribute used in the FXML. That attribute references the name "menuBar", which is (not coincidentally) also the name of the attribute in the controller class. In other words, the attribute fx:id="menuBar" ties the XML element that attribute is on in the FXML to the attribute with the same name in the controller.

I did not show much in this post specific to NetBeans 7.1, but it is worth noting that I had all the pertinent files created in a new project using NetBeans 7.1's New Project wizard and selecting a JavaFX FXML Application as the project type. This created a basic FXML file, a basic controller file, and a main class for loading the FXML and running the application. I modified these to the examples above for the FXML and for the controller class. The modified class that loads the FXML and starts the JavaFX application is shown next. (There's not a lot to it!)

JavaFxMenusWithFxmlDemo.java

package dustin.examples;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

/**
* Simple example of JavaFX 2 FXML used to demonstrate JavaFX 2 menus. This is a
* "port" of the example featured using "pure Java" (no FXML) in the post
* "(Pure Java) JavaFX 2.0 Menus"
* (http://marxsoftware.blogspot.com/2011/12/pure-java-javafx-20-menus.html).
*
* @author Dustin
*/
public class JavaFxMenusWithFxmlDemo extends Application
{
/**
* Main function for running this application.
*
* @param arguments Command-line arguments: none expected.
*/
public static void main(String[] arguments)
{
Application.launch(JavaFxMenusWithFxmlDemo.class, arguments);
}

/**
* Overridden Application.start(Stage) method.
*
* @param stage Primary stage.
* @throws Exception JavaFX application exception.
*/
@Override
public void start(final Stage stage) throws Exception
{
final Parent fxmlRoot = FXMLLoader.load(getClass().getResource("JavaFx2Menus.fxml"));
stage.setScene(new Scene(fxmlRoot));
stage.show();
}
}

I won't show the output here because it's essentially what the "pure Java" version produced, which is shown in my post on that approach. Besides generating the files that I adapted for my application, NetBeans 7.1's new project wizard for a JavaFX FXML application also created a project that automatically packages up what I need for my JavaFX application in an executable JAR. The contents of the JAR in this case are shown in the next screen snapshot.

The trickiest part about using FXML is the relatively less available documentation. The pure Java APIs have the strong Javadoc API documentation, but I know of no such thing for FXML (including no documentation or schema for the namespace http://javafx.com/fxml). There are some great resources of FXML such as Getting Started with FXML and Introduction to FXML. Perhaps the best document for figuring out what elements and attributes FXML provides is Introducing FXML: A Markup Language for JavaFX, which explains the "mapping" of JavaFX standard Java API classes to JavaFX FXML elements and attributes.

FXML appears to be a fairly attractive approach for building a JavaFX application because it nicely separates presentation (FXML) from business logic (controller class and classes that would be called by controller methods). This can make it easier to visually see the GUI layout in the hierarchical XML and keep the logic and presentation from cluttering each other.

Thứ Năm, 12 tháng 1, 2012

Revealing Project Naughtiness with Tattletale

Tattletale is a highly useful development tool that not only has a catchy name, but also has a clever slogan: "Betraying your project's naughty little secrets." Tattletale scours JAR files to find various naught little secrets about dependencies, multiple versions, extraneous versions of classes, JARs in multiple locations, and so forth. It is a simple tool that can be run from the command-line to generate simple HTML reports of multiple characteristics about JARs and classes.

To demonstrate Tattletale, I will execute it against a Spring Framework 2.5.6 installation. It is simple to run Tattletale and this is demonstrated in the next screen snapshot.

The tattletale.jar is an executable JAR and so is run with java -jar tattletale.jar. The first argument passed to it is the directory to be recursively searched (Spring 2.5.6 distribution in this case) and the second argument is the directory to which the HTML reports should be written (spring-output in this example). The directory listing of the spring-output directory is shown next.

As the two previous snapshots indicate, it is very straightforward to run Tattletale against a desired directory. A web browser can be used to open the index.html page as the starting page. This is shown in the next screen snapshot.

Only a subset of the available reports are shown in the above snapshot. Clicking on links brings up the individual reports. I show portions of select reports (circular dependencies, class locations, multiple copies of JARs, transitive dependencies, and transitive dependents) next.

Tattletale is so easy to use, very little documentation is necessary. However, there is a slide presentation and a User's Guide with introductory information. The 32-page User Guide covers running Tattletale (similar to this post) along with providing details on how to configure the tool via jboss-tattletale.properties and providing an overview of the many reports that Tattletale provides about one's project.

To address and correct a project's naughtiest little secrets, one must know what they are. Tattletale is an easy-to-use tool that exposes these naughty secrets so that they can be addressed.

Thứ Tư, 11 tháng 1, 2012

NetBeans 7.1's Unused Assignment and Dead Branch Hints

One of the new code hints provided by NetBeans 7.1 is the Unused Assignment hint. A simple code sample that will cause this hint to be displayed in NetBeans 7.1 is shown next.

Demonstrating Unused Assignment

/**
* Demonstrate NetBeans 7.1 code hint for situation in which variable
* assignment is made but never used.
*
* @return Integer.
*/
private static int demoUnusedAssignment()
{
int i = 2;
// ... do some good stuff, but without changing i's assignment or
// accessing i's value ...
i = 3;
return i;
}

In the code above, the local variable "i" is initialized to 2, but is never used and then is initialized again, making the first initialization unnecessary. The next image is a screen snapshot that shows NetBeans 7.1 displaying a warning code hint for the unused assignment.

As the above image indicates, NetBeans 7.1 warns of "The assigned value is never used."

The New And Noteworthy in NetBeans IDE 7.1 page mentions this hint among others and states:

Unused Assignment

A new pair of hints, Unused Assignment and Dead Branch, was introduced. The Unused Assignment finds values that are computed and assigned to a variable, but never used by reading the variable. The Dead Branch hint searches for branches of code that can never be executed.

Oh Dead Branch Hint, Where Art Thou?

The Unused Assignment Hint seems to work as suggested based on the example shown above. However, I have not been able to generate code that demonstrates the "Dead Branch" hint. I wonder if the Dead Branch hint is not yet supported and text related to it is not supposed to be under the "Unused Assignment" heading.

The following code contains a listing with several methods that I would expect might potentially lead to a warning about a dead code branch. None of these cause this code hint to appear in any form (warning or error) in my installation of NetBeans 7.1.

Methods With Compilable Dead Code Branches

package dustin.examples;

import static java.lang.System.out;

/**
* Class demonstrating NetBeans 7.1's hint for dead code.
*
* @author Dustin
*/
public class DeadCode
{
/**
* Nonsense method that includes an "else" clause that can never be executed.
*
* @param someInt Any primitive int.
*/
private static void neverExecutedElse(final int someInt)
{
if (someInt < 0)
{
out.println("The integer you provided is less than zero.");
}
else if (someInt > 0)
{
out.println("The integer you provided is greater than zero.");
}
else if (someInt == 0)
{
out.println("The integer is equal to zero.");
}
else
{
out.println("Unable to categorize provided integer.");
}
}

/**
* Nonsense method that has executable code following conditions that are
* always true and always lead to premature termination of the method.
*/
private static void codeAfterAlwaysTrueConditional()
{
if (true)
{
throw new RuntimeException("Ouch!");
}
final String nothingHere = "Nothing here.";
out.println(nothingHere);

if (true)
{
return;
}
final String nothingHereEither = "Nothing here either.";
out.println(nothingHereEither);
}

/**
* Nonsense method that prints text to standard output only if the provided
* boolean can be both {@code true} and {@code false} at the same time.
*
* @param boolValue Boolean value of no consequence.
*/
private static void cannotHaveItBothWays(final boolean boolValue)
{
if (boolValue)
{
if (!boolValue)
{
out.println("Make up your mind (true or false)!");
}
}
else
{
if (boolValue)
{
out.println("Make up your mind (false or true)!");
}
}
}

/**
* Runs else-if that is same as previous if such that one conditonal
* prevents the second conditional's implementation from ever being executed.
*
* @param boolValue A boolean value of no consequence.
*/
private static void pesterUntilItWorks(boolean boolValue)
{
boolValue = true;
if (boolValue)
{
out.println("It matches once.");
}
else if (boolValue)
{
out.println("It matches twice.");
}
else if (!boolValue)
{
out.println("No match once.");
}
else if (!boolValue)
{
out.println("No match twice!");
}
}

/**
* Cover all conditions in first conditional and include a never-can-happen
* else portion of conditional.
*/
private static void completeConditionalCoverage()
{
boolean boolValue = true;
if (boolValue || !boolValue)
{
out.println("I'm always going to happen.");
}
else
{
out.println("I'm never going to happen.");
}

if (boolValue && !boolValue)
{
out.println("I'll never happen either.");
}
else
{
out.println("I'll also always happen.");
}
}

/**
* Main executable function.
*
* @param arguments Command-line arguments: none expected.
*/
public static void main(final String[] arguments)
{
if (false)
{
neverExecutedElse(5);
codeAfterAlwaysTrueConditional();
cannotHaveItBothWays(true);
pesterUntilItWorks(true);
demoUnusedAssignment();
completeConditionalCoverage();
}
}
}

Although none of the methods in the directly previous code listing lead to the Dead Branch code hint, NetBeans 7.1 does include configuration options for the Dead Branch hint. This is shown in the next screen snapshot (selecting Tools->Options followed by the "Editor" tab and then selecting "Hints").

The NetBeans 7.1 News and Noteworthy page shows examples of other new hints, but does not show an example of the Dead Branch hint. Also, the text talking about Dead Branch is mixed with the section on Unused Assignment and under a heading that only talks about Unused Assignment. As my previous code listing demonstrates, I attempted to come up with a code sample to demonstrate the Dead Branch hint, but have not been able to do so. The purpose of this hint ("search[ing] for branches of code that can never be executed") sounds like a nice complement to compiler errors such as "unreachable statement" and "exception already caught" and other NetBeans "green" warnings such as "variable such-and-such is not used."

I have blogged about NetBeans hints before and the addition of new hints in NetBeans 7.1 is welcome. If anyone knows of a code sample that will demonstrate the Dead Branch hint in NetBeans 7.1, please share!

Thứ Hai, 9 tháng 1, 2012

Comparing Heap Dumps with NetBeans 7.1

One of the "new and noteworthy" features of NetBeans 7.1 is the ability to compare two heap dumps. Specifically, the easy-to-use feature allows one to quickly ascertain the difference in number of each class's instances between two dump files. This brief post shows how easy it is to use.

Heap dumps can be generated in a variety of ways. For purposes of this post, I have created two heap dumps on two totally separate applications using the Oracle JDK-provided jmap (Java Memory Map) tool to attach to the processes's Java PIDs and create heap dumps (creatively named Heap1.map and Heap2.map in my example). It's probably not useful in most cases to compare heap dumps of two entirely different applications. I only do so in this example to make the differences calculated in the comparison results obvious.

The next screen snapshot shows NetBeans 7.1 started with the option "Load heap dump..." being selected under the "Profile" menu. This is done to load the first heap dump of the two to be compared.

The next screen image shows the results of selecting "Load heap dump..." (the popup titled "Open Heap Dump File") and indicates selecting one of the heap dumps (Heap1.map).

The next screen snapshot shows how NetBeans 7.1 looks with the selected heap dump displayed with the "Summary" tab in focus.

The last image showed the heap file loaded in NetBeans 7.1 with the "Summary" tab in focus. The next image is a snapshot of the IDE switched to the "Classes" tab in the heap dump report area.

The last image indicates that NetBeans shows the number of instances of different classes in the Java application whose heap dump is being analyzed. By default, the instances are listed in descending order of number of instances, but one can click on the "Size" column header to sort by total size. Just above the column headings "Instances" and "Size" is a link that says, "Compare with another heap dump" and that is the main focus of this post.

Clicking on the "Compare with another heap dump" link in the "Classes" tab of NetBeans 7.1's heap dump analysis tool leads to a popup ("Select Heap Dump to Compare") for selecting the second heap dump to be compared. This is indicated in the next screen snapshot.

In my example, I had two other heap dump files in the same directory as the originally selected one (Heap2.map and Heap3.map). Selecting Heap3.map leads to the comparison being made. This can take a few seconds for the NetBeans IDE to update the representation and it might be worth moving the scroll bar on the right down and back up to make sure it has updated. The next two screen snapshots show the comparison displayed with the first screen snapshot showing the types for which the first heap dump has more instances than the other (top) and the second image showing the types for which the second heap dump has more instances than the other (bottom).

The + and - signs indicate the number of instances greater (+) or fewer (-) in the first heap dump file analyzed (Heap1.map) as compared to that of the second heap dump file analyzed (Heap3.map). In other words, types with positive numbers have more instances represented in the originally loaded heap dump and types wiuth negative numbers have fewer instances represented in the originally loaded heap dump.

When comparing two separate applications, this doesn't provide much that's interesting other than to illustrate the tool. However, given two instances of the same application at the same execution point with different context or data sets might prove more interesting when comparing heap dumps. Perhaps the most enlightening use of this tool is for comparing heap dumps taken from the same application at different points in its execution. With NetBeans 7.1, it is easy to rapidly determine the difference between two heap dumps in terms of instances loaded at the time each heap dump was taken. When it's the delta or difference that matters, this tool can be useful.

Thứ Bảy, 7 tháng 1, 2012

First Impressions of Book 'JBoss AS 7 Configuration, Deployment and Administration'

Packt Publishing recently invited me to review the book JBoss AS 7 Configuration, Deployment and Administration. I readily accepted because I have not used or even read about JBoss in several years and welcomed the opportunity to read about its latest features. In this post, I provide a very brief first impression of the PDF version of this book similar to the brief preliminary review I previously provided of the Packt book Java EE 6 Development with NetBeans 7. I intend to provide a more thorough review of JBoss AS 7 Configuration, Deployment and Administration in a future post with a level of detail similar to that I provided for Java EE 6 Development with NetBeans 7.

The subtitle of author Francesco Marchioni's book JBoss AS 7 Configuration, Deployment and Administration is: "Build a fully-functional, efficient application server using JBoss AS." The "About the Author" section of the book states that Marchioni runs the site http://www.mastertheboss.com/, which has a main page with the subtitle "JBoss and Java EE tutorials." Two links currently shown on that main page are to posts about publication of JBoss AS 7 Configuration, Deployment and Administration and about winning a free copy of JBoss AS 7 Configuration, Deployment and Administration. Marchioni has also written the books JBoss AS 5 Development and JBoss AS 5 Performance Tuning.

The Packt Publishing page for JBoss AS 7 Configuration, Deployment and Administration provides a look at the book's Table of Contents, provides a free sample chapter, and provides more details on what the book covers.

Perusing the Table of Contents of JBoss AS 7 Configuration, Deployment and Administration leads me to believe that the 11 chapters will provide broad coverage of administrating and developing with JBoss AS 7. The chapters include the titles Installing JBoss AS 7, Configuring the Application Server, Configuring Enterprise Services, JBoss Web Server Configuration, Configuring a JBoss AS Domain, Deploying Applications on JBoss AS 7, Managing the Application Server, Clustering, Load-balancing Web Applications, Securing JBoss AS 7, and the particular trendy title Taking JBoss AS 7 in the Cloud. The Appendix looks useful with sections summarizing options and commands for JBoss 7 Command Line Interface (CLI).

I look forward to reading JBoss AS 7 Configuration, Deployment and Administration and learning more about JBoss AS 7. I will post a lengthier review based on my experience reading it.