Apr 15, 2010

Comparison of Enhancements in Java 1.4, Java 1.5 and Java 6.0

What is Java?

Java is a programming language expressly designed for use in the distributed environment of the Internet. It was designed to have the "look and feel" of the C++ language, but it is simpler to use than C++ and enforces an object-oriented programming model. Java can be used to create complete applications that may run on a single computer or be distributed among servers and clients in a network. It can also be used to build a small application module or applet for use as part of a Web page. Applets make it possible for a Web page user to interact with the page.

The Java Programming Language is a general-purpose, concurrent, strongly typed, class-based object-oriented language. It is normally compiled to the bytecode instruction set and binary format defined in the Java Virtual Machine Specification.

Main Characteristics of JAVA

  • Java is object-oriented
  • Java is robust
  • Relative to C++, Java is easier to learn.
  • In addition to being executed at the client rather than the server, a Java applet has other characteristics designed to make it run fast.
  • Portability

In this article we will explore various enhancements of Java 1.4, Java 1.5 and Java 6 and compare them accordingly.

Java 4:

Java 1.4 is one of the earlier versions of Java family. Java’s up gradation began swiftly on release of Java 1.4. It is code named as Merlin.

Assertion:

The assertion is an amazing programming facility introduced in JDK 1.4 that helps you debug and maintain your Java code. Basically, an assertion is a statement in the Java programming language that enables you to test your assumptions about a program. Let's take a closer look at how you can put assertions to work.

An assertion is a statement that tests a condition, somewhat as an if statement does. When the condition is violated, it triggers an error so that you know where to revise the assumption. This is a facility to reduce the error chances, especially for those beyond expectations.

The assertion is specifically designed for debugging, while the other methods are used mainly for production. Assertions are a tool of testing whether your logic is correct rather than capturing uncontrollable exceptions.

If-then-else style:

if (i % 3 != 0)
{
if (i < 0)
{
System.err.println("Error in Variable i");
return -1;
}
System.out.println("Change $"+i%3);
Assertion style:
if (i % 3 != 0)
{
assert i > 0;
System.out.println("Change $"+i%3);
}
}

If the variable i is exceptionally smaller than zero, the first block of code signals Error in Variable i. The second case throws an assertion error indicating the line where the error occurred. Obviously, the assertion requires far fewer lines.

Regular Expression:

Regular Expressions are basically patterns of characters which are used to perform certain useful operations on the given input. The operations include finding particular text, replacing the text with some other text, or validating the given text. For example, we can use Regular Expression to check whether the user input is valid for a field like Email Id or a telephone number.

The java.util.regex package provides the necessary classes for using Regular Expressions in a java application. This package has been introduced in Java 1.4. It consists of three main classes namely,

  • Pattern
  • Matcher
  • PatternSyntaxException

Pattern:

A regular expression which is specified as a string, should be first compiled into an instance of Pattern class. The resulting pattern can then be used to create an instance of Matcher class which contains various in-built methods that helps in performing a match against the regular expression. Many Matcher objects can share the same Pattern object.


  • compile() method
  • matcher() method
  • matches() method
  • pattern() method
  • split() method
  • flag() method

Matches:

The Matcher class which contains various in-built methods such as matches(), find(), group(), replaceFirst(), replaceAll() etc., that help us to check whether the desired pattern occurs in the given text or search the desired pattern in the text or to replace the occurrence of the pattern in the text with some other set of characters as per the requirement.

  • matches() method
  • find() method
  • group() method
  • start() method and end() method

Example:

public class RegExpTest
{
public static void main(String[] args)
{
String inputStr = "Computer";
String pattern = "Computer";
boolean patternMatched = Pattern.matches(pattern, inputStr);
System.out.println(patternMatched);
}
}

Pattern Syntax Exception:

A PatternSyntaxException object is an unchecked exception that indicates a syntax error in a regular expression pattern.

Logging:

Logging is a new API added in J2SE 1.4 to provide advanced control of informational output from programs. It's targeted at four principal use cases:

  • Problem diagnosis by end users and system administrators, reporting common problems with local fixes. For example, an out of disk space error.
  • Problem diagnosis by field service engineers. More verbose than the above, these reports would help find performance or other configuration errors.
  • Returning detailed information for diagnosis by the development team. For example, writing out detailed tracing information.
  • Problem diagnosis by developers, watching code execution directly.

The entire logging API is contained in the package java.util.logging and is made up of the following interfaces and classes:

  • ConsoleHandler
  • FileHander
  • Filter
  • Formatter
  • Handler
  • Level
  • Logger
  • LoggingPermission
  • LogManager
  • LogRecord
  • MemoryHandler
  • SimpleFormatter
  • SocketHandler
  • StreamHandler
  • XMLFormatter

The ConsoleHandler and the FileHandler are probably the most popular ones, covering most applications basic needs.

Finally we have the Formatters. As their name imply they determine the layout of the messages. Sun has defined two formatters:

  • SimpleFormatter: defines a simple message format containing among other things a timestamp
  • XMLFormatter: a message in XML format

Every handler has an associated formatter.

Consider an example,

public class HelloWorld
{
public static void main(String[] args)
{
HelloWorld hello = new HelloWorld("Hello world!");
hello.sayHello();
}
private String theMessage;
public HelloWorld(String message)
{
theMessage = message;
}
public void sayHello()
{
System.err.println(theMessage);
}
}


We will expand upon this simple program in order to demonstrate and motivate the logging API. The first thing we will do is actually generate a logging message. This is straightforward; we need to create a Logger object, which represents the HelloWorld class, like this:


package logging.example2;
import java.util.logging.Logger;
public class HelloWorld
{
private static Logger theLogger =
Logger.getLogger(HelloWorld.class.getName());
public static void main(String[] args)
{
HelloWorld hello = new HelloWorld("Hello world!");
hello.sayHello();
}
private String theMessage;
public HelloWorld(String message)
{
theMessage = message;
}
public void sayHello()
{
System.err.println(theMessage);
}
}


Logging Levels


Because we want to leave logging code in an application that goes into production, we need logging to cost us very little at runtime when it is not being used. To help achieve this, the logging system defines a class called Level to specify the importance of a logging record. The logging library has a set of predefined logging levels:


SEVERE The highest value; intended for extremely important messages (e.g. fatal program errors).
WARNING Intended for warning messages.
INFO Informational runtime messages.
CONFIG Informationalmessages about configuration settings/setup.
FINE Used for greater detail, whendebugging/diagnosing problems.
FINER Even greater detail.
FINEST The lowest value; greatest detail.


In addition to these levels, there is a level ALL, which enables logging of all records, and one called OFF that, can be used to turn off logging. It is also possible to define custom levels, but in this article we will stick with the predefined levels.


Java 5:


Java is more robust than ever, with the introduction of Java 5. Java 5 was released with many new and exciting features that made Java even easier to use. Here we are going to explain the features of JAVA 5 with respect to previous versions of Java. Tiger is the code name of Java 5.


Enhancements in JDK 5


Generics:


This feature of Generics in Java 5 allows application to create classes and objects that can operate on any defined objects. Generic programming enables Classes and Methods to operate on well defined parametric types allowing clients to substitute a suitable Java type during compilation.


Example:


The following code shows explicit casting in Java 4 which has no feature of Generics.


Map contacts = new HashMap();
contacts.put(new Long(9912345678L), "Jenny");
contacts.put(new Long(9912345679L), "Johny");
Set contactValues = contacts.entrySet();
Iterator contactIterator = contactValues.iterator();
while (contactIterator.hasNext())
{
Map.Entry anEntry = (Map.Entry)contactIterator.next(); //Line A
Long number = (Long)anEntry.getKey(); // Line B
String name = (String)anEntry.getValue(); // Line C
System.out.println(number + ":" + name);
}


Even though we know that we add phone number and name, we do explicit cast to get them in line A, B, C. It would create problem if client need to put some other data other than Long.


Solution to above problem is Generics in Java 5. Following is the code using generics.


Map<Integer, String> contacts = new HashMap<Integer, String>();
contacts.put (new Integer (99999), "kskh");
contacts.put (new Integer (67897),"hbjbu");
Set<Map.Entry<Integer, String>> contactValues = contacts.entrySet ();
Iterator<Map.Entry<Integer, String>> entryIterator = contactValues.iterator ();
while (entryIterator.hasNext ())
{
Map.Entry<Integer, String> anEntry = entryIterator.next();
Integer number = anEntry.getKey ();
String name = anEntry.getValue ();
System.out.println (number+":"+name);
}


The declaration Map contacts = new HashMap (); in previous example has now changed to Map<Long, String> contacts = new HashMap<Long, String> ();


The former is called a Raw Map and the latter is an example of a Generic Map.


Enhanced for Loop:


The enhanced for-loop is just a convenience from the programmer's point of view for iterating over the Collection. But it has got its own disadvantages which will be discussed later.


Consider a simple code to print array in order:


int arr[5] = {2,4,8,16,32};

for (int i=0; i<5; i++)

System.out.println ("Output: " + arr[i]);


The main intension is to print the array in order. This can be done in simpler way using Enhanced for loop in Java 5 as below.


for (int a: arr)


System.out.println("Output: "+ a);


This enhanced for loop holds good for Map, List, Queue, Set and other collections.


Disadvantages of Enhanced for Loop:


1) Step value cannot be incremented. For example it is not possible to traverse from first value to third value.


2) Backward traversal is not possible.


Autoboxing/Unboxing


Autoboxing is an exciting feature of Java 5 that makes a programmers work much easier when it comes to working with primitive wrapper types. Conversion of primitive types to their object equivalents in method and construction invocation is known as autoboxing.


Java 5 also supports automatic unboxing, where wrapper types are automatically converted into their primitive equivalents if needed for assignments or method or constructor invocations.


Before Java 5.0, we could not put primitive values like int, long, float, double, char etc. into collections as they are not objects. Collections can hold object references, so we were required to use wrapper classes.


Consider the following example:


int a = 10;


Vector vt = new Vector ();


vt.add (new Integer (a));


int n = ((Integer) vt.elementAt (0)).intValue ();


In the above example we want to store an int “a” into vector “vt”, we have to use wrapper class. And if we want to get element stored at position “0” of vector “vt”, we again have to do casting.


If we want to do same coding in Java 5, it would be much easier because of autoboxing feature.


int a = 10;


Vector <integer> vt = new Vector <integer> ();


vt.add (a);


int n = vt.elementAt (0);


Advantages of Autoboxing:


1) Autoboxing/unboxing removes the pain of manual conversion between primitives and wrappers as the compiler creates code to implicitly create objects for us.


2) Auto-Boxing works also in comparisons (==, <, >, etc.).


Disadvantages of Autoboxing:


1) SUN recommends using them only when there is an “impedance mismatch” between reference types and primitives, for example, when you have to put numerical values into a collection.


2) It is not appropriate to use autoboxing and unboxing for scientific computing, or other performance-sensitive numerical code.


3) Autoboxing and unboxing blur the distinction between primitive types and reference types


TypeSafe Enums:


Of all enhanced features of Java 5, TypeSafe Enumeration has been considered as the most exciting feature. The omission of proper enumeration in previous version of Java annoyed many developers.


Let us take up an example to see what difference Enum feature has made in developers life.


class FizzyDrink { static final int PEPSI = 1; static final int COKE = 2; static final int SCHWEPPES = 3 }


On taking a plain look on the above code we might think that there are 3 fizzy drinks. Actually it is not. It has just 3 int values. Consider the following code,


int todaysFizzyDrink = 237;


This is not possible. This is called type un-safe, which means the compiler isn't able to force users of our class to use one of the acceptable values we've defined.


The same code written with enum in Java 5.


enum FizzyDrink{ pepsi, coke, schweppes }


Here you can see enum keyword is replaced with class. With enum you can create type safe code.


FizzyDrink todaysFizzyDrink = FizzyDrink.pepsi;


If we print the value of todaysFizzyDrink, we would get the string pepsi and not some meaningless integer value.


Advantages of Enum:


1) You can use enums as case labels.


2) Enums are type safe. With Strings all your items in all categories are the same type.


3) You can compare enums quickly with ==. You don’t need to use equals as you do with String.


Disadvantages of Enum:


1) You can’t create new enum constants at run time. You must recompile. In contrast, it is easy to add another String to an array or ArrayList.


2) You have to create en entire new class for each enum.


3) You can’t create derived enum classes with a few extra enum constants. You can fairly easily add a few more Strings to a List.


Varargs:


Java 5 provides added convenience of using variable parameters, known as varargs. There may be a situation where you need to pass in many instances of the same object type to a method, but you don't know at compile time how many instances there will be. In the past, the only way to handle this situation was to bundle these objects in an array or other collection.


Let us take up an example to illustrate varargs,


class VarGreeter
{
public static void printGreeting (String... names)
{
for (String n: names)
{
System.out.println ("Hello” + n + ". ");
}
}
public static void main(String[] args)
{
printGreeting("
Paul", "Sue");
}
}


In general, a method can have at most one parameter that is a vararg, it must be the last parameter taken by the method, and it is denoted by the object type, a set of ellipses (...), and the name of the variable.


Varargs application can be used with constructors also. In this it will choose the constructor that is more specifically matching one.


public class WhichOne
{
WhichOne(Integer... size)
{
System.out.println("Var Args version.");
}
WhichOne(int i, int j)
{
System.out.println("Version with int args.");
}
WhichOne(Integer i, Integer j)
{
System.out.println("Version with Integer args.");
}
public static void main(String[] args)
{
System.out.println("Call w/ two arg:2,3");
new WhichOne(2, 3);
System.out.println("Call w/ Integer two arg: 2,3");
new WhichOne(new Integer(2), new Integer(3));
}
}


Important Notes on Varargs:


1. Method with varargs is called only when no other method signature matches the invocation.


2. Only one varargs per method can be declared.


3. Varargs should be the last argument(set) for a method. So public void varargtest (int i, String … args) is valid but public void varargtest (String … args, int i) is not.


4. Zero or more arguments can be passed for varargs unlike an array where at least a null has to be provided.


Limitations:


1. Varargs can be used as a last input parameter


2. If there are no input values of the varargs type input parameter then there must be at least one “null” value to succeed compilation.


Static Import:


This feature of Java5 enables user to enables to perform static import declaration which enables programmers to refer to imported static members as if they were declared in the class that uses them.


By adding the word static after the import keyword, you change your import to a static one. When an import is static, all the accessible methods and variables of the class can be used without prefixing its access with the class name.


There are two types of Static Imports:


1) Import of particular static member of a class. Ex: import static packageName.ClassName.staticMemberName;


2) Import of all static members of a class. Ex: import static packageName.ClassName.*;


Consider the following example:


import static java.awt.Color.*; //Line 1
public class hai
{
public static void main(String args[])
{
System.out.println(RED); //Line 2
}
}


In the above example, line 1 represents the usage of static import. Line 2 represents the usage of static member of class Color RED is used without dot(.) and Class name before its member name.


Had we not used static import in Line 1, Line1 and Line 2 should have been represented as


import java.awt.*;


// code here


System.out.println(Color.RED);


Advantages and Disadvantages:


Some times static import can cause maintenance problem at times and it is recommended to use static import in the appropriate circumstances


Annotations:


Annotations in Java are all about adding meta-data facility to the Java elements. Like Classes, Interfaces or Enums, Annotation define a type in Java and they can be implemented in several other Java elements.


Annotations provide data about a program that is not part of program itself. They have no direct effect on operation of the code they annotate.


Uses of Annotation:


1) Information for the compiler


2) Compiler-time and deployment-time processing


3) Runtime processing


4) It is advisable to use annotation instead of commenting lines to make any important information.


Types of Annotations:


1) Annotation Type.


2) Annotation.


Annotation Type:


An annotation type definition takes an "at" (@) sign, followed by the interface keyword plus the annotation name.


Example:


@interface ClassPreamble
String author();
String date();
int currentRevision () default 1;
String lastModified () default "N/A";
String lastModifiedBy () default "N/A";
String [] reviewers (); // Note use of array
}


Annotation:


An annotation takes the form of an "at" sign (@), followed by the annotation type. This is simplest form of annotation


Example:


@ClassPreamble (
author = "John Doe",
date = "3/17/2002",
currentRevision = 6,
lastModified = "4/12/2004",
lastModifiedBy = "Jane Doe",
reviewers =
{
"Alice", "Bob", "Cindy"
}
// Note array notation
)
public class Generation3List extends Generation2List
{
// class code goes here
}


Advantages and Disadvantages of Using Annotations:


Metadata annotations are relatively simple to use and understand. They provide in-line metadata located with the code that this metadata is describing–you do not need to replicate the source code context of where the metadata applies.


On the other hand, annotations unnecessarily couple the metadata to the code. Thus, changes to metadata require changing the source code.


Swings:


Swing, which is an extension library to the AWT, includes new and improved components that enhance the look and functionality of GUIs. Swing can be used to build Standalone swing GUI Apps as well as Servlets and Applets. It employs a model/view design architecture. Swing is more portable and more flexible than AWT.


Some advantages of Java Swings are



  • Extensibility
  • Customizable
  • Configurable
  • Lightweight UI
  • Loosely Coupled - MVC Architecture
  • Pleasant look and feel

Example:


import javax.swing.JFrame;
public class Simple extends JFrame
{
public Simple()
{
setSize(300, 200);
setTitle("Simple");
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
Simple simple = new Simple();
simple.setVisible(true);
}
}


While this code is very small, the application window can do quite a lot. It can be resized, maximized, minimized. All the complexity that comes with it has been hidden from the application programmer.


import javax.swing.JFrame;


Here we import the JFrame widget. It is a toplevel container, which is used for placing other widgets.


setSize (300, 200);


setTitle ("Simple");


This code will resize the window to be 300px wide and 200px tall. It will set the title of the window to Simple.


setDefaultCloseOperation (EXIT_ON_CLOSE);


This method will close the window, if we click on the close button. By default nothing happens.


clip_image002


Swing Design Pattern:


Swing engineers created the Swing toolkit implementing a modified Model View Controller design pattern. This enables efficient handling of data and using pluggable look and feel at runtime.


The traditional MVC pattern divides an application into three parts. A model, a view and a controller. The model represents the data in the application. The view is the visual representation of the data. And finally the controller processes and responds to events, typically user actions, and may invoke changes on the model. The idea is to separate the data access and business logic from data presentation and user interaction, by introducing an intermediate component: the controller.


The Swing toolkit uses a modified MVC design pattern. The Swing has single UI object for both the view and the controller. This modified MVC is sometimes called separable model architecture.


In the Swing toolkit, every component has it's model. Even the basic ones like buttons. There are two kinds of models in Swing toolkit.



  • state models
  • data models

The state models handle the state of the component. For example the model keeps track whether the component is selected or pressed. The data models handle data, they work with. A list component keeps a list of items, it is displaying.


For Swing developer it means that we often need to get a model instance in order to manipulate the data in the component. But there are exceptions. For convenience, there are some methods that return data without the model.


For example the getValue () method of the JSlider component. The developer does not need to work with the model directly. Instead, the access to the model is done behind the scenes. It would be an overkill to work with models directly in such simple situations. Because of this, the Swing tookit provides some convenience methods like the previous one.


To query the state of the model, we have two kinds of notifications.



  • lightweight notification
  • stateful notification

The lightweight notification uses a ChangeListener class. We have only one single event (ChangeEvent) for all notifications coming from the component. For more complicated components, the stateful notification is used. For such notifications, we have different kinds of events. For example the JList component has ListDataEvent and ListSelectionEvent.


If we do not set a model for a component, a default one is created. For example the button component has DefaultButtonModel model


Components of Swings:



  • JList Component
  • JTextArea component
  • JTextPane component JFrams
  • Jwindow
  • JOptionPane
  • JLabel
  • JTextFeild
  • JPasswordFeild
  • JButton
  • JCheckBox
  • JComboBox
  • JTabbedPane

Java 6:


One of the principal design centres for Java Platform, Standard Edition 6 (Java SE 6) was to improve performance and scalability by targeting performance deficiencies highlighted by some of the most popular Java benchmarks currently available and also by working closely with the Java community to determine key areas where performance enhancements would have the most impact.


Java 6 is also known as Mustang. Though there are no significant changes at the Language Level compared to Java 5, though Mustang comes with a bunch of enhancements in the other areas like Core, XML and Desktop. Most of the features are applicable both to J2SE and J2EE Platforms.


Brief notes on Java 6:



  • Developed using open source model
  • All development releases were made publicly available
  • Finally released in December 2006
  • No syntax or language structure changes
  • Most notable features
  • Speed!
  • Improved desktop L&F and integration
  • New / improved diagnosing & management tools
  • Significant API improvements.

Enhanced Features of Java 6:



  • Scripting
  • Web Services
  • Database (JDBC 4.0, Java DB)
  • More Desktop APIs
  • Monitoring and Management
  • Compiler Access
  • Pluggable Annotations
  • Desktop Deployment
  • Security
  • Quality, Compatibility, Stability

Scripting:


Motivation for Scripting:



  • Provides developers an opportunity to leverage the advantages of different languages in the same application
  • Extends scripting languages using the powerful Java technology libraries
  • Reuse of code modules in other programming languages
  • Produces an environment in which developers and end users can collaborate to create more useful, dynamic applications
  • By delivering Java applications that can be customized via scripts by users of the applications

Scripting



  • Scripting for the Java Platform (JSR 223)
  • Mechanism for configuring script engines into Java SE
  • APIs for mixing script fragments into Java applications
  • A JavaScript engine is included in Sun's implementation of Java SE 6
  • Mozilla Rhino engine
  • Conformant scripting engines
  • scripting.java.net

Scripting Support



  • JDK 6 introduces inherent support for VM hosted scripting languages
  • Java 6 comes with the JavaScript engine (code name Rhino) as default
  • Scripting API already supports 33 different script / script dialects
  • The API provides rich tools for two-way script binding
  • Java to script: call Java objects from script
  • Script to Java: Script object available to Java code

Example:


Scripting – Developer Example


// create a ScriptEngineManager
ScriptEngineManager m = new ScriptEngineManager();
// get an instance of JavaScript script engine
ScriptEngine engine = m.getEngineByName ("js");
// evaluate a script
engine.eval ("alert (\"Hello World!\")");


Web Services Support on Java SE 6 Platform



  • JAX-WS
  • Data binding using JAXB 2.0
  • Updates to the JAXP, which includes StaX
  • Standards supported
  • SOAP 1.2
  • WS-I Basic Profile 1.1
  • XML-binary Optimized Packaging (XOP) and SOAP Message
  • Transmission Optimization Mechanism (MTOM)
  • Representational State Transfer (REST)
  • Totally on XML schema

API Support:



  • Java SE 6 provides support for the JAX- WS web services stack.
  • For the client side: Service class for creating proxy
  • For the server side: Endpoint class for publication

Server-Side Programming Model:



  • Write a Plain Old Java Object (POJO) implementing the service.
  • Add @WebService to it.
  • Optionally, inject a WebServiceContext
  • Publish the Web service endpoint through Endpoint.publish() method
  • WSDL is automatically generated at runtime
  • Point your clients at the Web Services Description Language (WSDL), for example:
  • http://myserver/myapp/MyService?WSDL.
  • The publish methods can be used to start publishing an endpoint, at which point it starts accepting incoming requests.
  • The stop method can be used to stop accepting incoming requests and take the endpoint down
  • Publish using the HTTP server embedded in Java SE 6.
  • Supports reasonable defaults for threading.
  • Creates WSDL and publishes it at runtime in http://localhost/calculator?WSDL

Example:


Publishing an Endpoint
@WebService
public class Calculator
{
@Resource
WebServiceContext context;
public int add(int a, int b)
{
return a+b;
}
}
// Create and publish an endpoint
Calculator calculator = new Calculator ();
Endpoint endpoint = Endpoint.publish
(“http://localhost/calculator”, calculator);


Client-side Programming



  • Point a tool at the WSDL for the service
  • Generate annotated classes and interfaces through a tool
  • Call new on the service class.
  • Get a proxy using a getxxxPort method.
  • Invoke any remote operations.

Example:


Java SE-based Client
// Create a Service object
CalculatorService svc = new
CalculatorService ();
// Create a proxy from the Service object
Calculator proxy =
svc.getCalculatorPort ();
// Invoke a Web service operation
int answer = proxy.add(35, 7);


Web Service



  • Inherent support for web services
  • Uses the newly redesigned Java API for XML Web Services (JAX-WS 2.0)
  • Create services using annotated POJO's
  • JDK now includes WS tools
  • wsgen to generate web service artifacts
  • simport to create client artifacts from WSDL
  • Built-in lightweight http server
  • Monitoring & Management

Database


JDBC 4.0 Support



  • Updated the developer APIs (JDBC 4.0 )
  • Exception handling improvement
  • New subclasses of SQLException
  • Enhanced BLOB/CLOB functionality
  • SetClob(), createClob()
  • SQLXML Data Type (from SQL 2003)
  • XML is a first-class data type – no longer need to use CLOBs to access XML data element

Java DB



  • Java DB based on Apache Derby
  • JDBC conformant all-Java relational database
  • Bundled and pre-configured in JDK

Database – Java DB



  • JDK 6 includes bundling of Java DB aka
  • Apache Derby
  • 100% Java implemented database engine
  • Features include
  • Standard SQL / JDBC support
  • Full transaction support
  • Security features include SSL
  • Ideal as an embedded database (only 2 MB)
  • Robust enough for client-server applications

Database – JDBC 4



  • New JDBC 4 API bundled with JDK 6
  • Simpler developer-friendly annotation-based
  • API for retrieving/updating data
  • Improved support for SQL 2003 data types including CLOB, BLOB, Array, Struct, Ref, and RowID
  • XML data type (SQLXML) is now first-class SQL type with full API support

Desktop APIs


AWT improvements



  • Tray icon
  • Splash screen
  • Desktop class
  • Dialog Modality enhancements and API
  • Text printing

Swing improvement



  • GroupLayout – basis for NetBeans GUI Builder (Matisse)
  • JTable sorting and filtering
  • SwingWorker

Tray Icon


Lets you access the system tray in your Java application



  • SystemTray
  • TrayIcon

Give you the ability to add graphics, popup menus, and floating tip functionality to the system tray.


Tray Icon: Usage


// Construct a TrayIcon
TrayIcon trayIcon = new TrayIcon (image, "Tray Demo",
popupMenu);
// Add event listener
trayIcon.addActionListener(actionListener);
// Add the tray icon to the System tray
SystemTray.getSystemTray().add(trayIcon);


Splash Screen:


Before Java SE 6, Java runtime needs to be fully loaded and initialized before a visual image can be displayed. It allows displaying a splash screen for the application instantly—before the Java runtime software starts.



  • GIF, PNG, and JPEG images supported
  • Transparency, translucency, and animation supported
  • Closed automatically when first top-level window displays

Splash Screen: Example



  • Display from command line java -splash:image.gif TheApp
  • Display from MANIFEST.MF (in a jar file) Splashscreen-Image: mage.gif
  • Painting - You can change the image shown after
  • The splash screen is loaded, but before the application starts.
  • SplashScreen splash =SplashScreen.getSplashScreen();
  • Graphics2D g = splash.createGraphics();
  • // your painting code here
  • splash.update();

Desktop Class


New class: java.awt.Desktop



  • Has an enumeration of actions that may be supported for a file or URI
  • BROWSE, EDIT, MAIL, OPEN, and PRINT

Depends on platform capabilities to work:



  • Desktop.isDesktopSupported()

File processing:



  • Opening, editing, and printing files with applications registered in native system

Browsing:



  • Opening a URL with the default browser

Email:



  • Sending a message with the default mail client

Dialog Modality Enhancement


New modality model is introduced



  • This new model allows the developer to scope, or limit, a dialog box's modality locking, based on the modality type that the developer chooses
  • Allows windows and dialog boxes to be truly parentless
  • Solves the problem of interacting with JavaHelp in J2SE1.5 when modal dialog box is on the front

Modality Types


Modeless



  • Does not block any other window

Document-modal



  • Blocks input to all top-level windows from the same document

Application-modal



  • Blocks all windows from the same application

Toolkit-modal



  • Blocks all windows that run in the same toolkit

Text Printing


Easily print a Swing text component:



  • Prints the entire contents of the text component
  • Does not have to be visible
  • javax.swing.text.JTextComponent.print()

Reformats for printed page.


Optionally displays print dialog and progress box.


Supports optional header/footer.


It will not split lines in half.


Swing Worker:



  • Makes it easy to offload work to separate threads
  • Makes use of concurrency package
  • Makes it more generic
  • Supports partial results
  • Supports PropertyChangeListener
  • More capabilities for relative positioning of components
  • Works with horizontal and vertical layout separately

Layout Arrangements in GroupLayout:



  • Hierarchically groups components to position them in a Container.
  • Supports two types of groups:

A sequential group positions its child elements sequentially, one after another.


A parallel group aligns its child elements in one of four ways.



  • Each group may contain any number of elements, where an element is a Group, Component, or gap.
  • Layout is defined for each dimension independently.

Using Group Layout Class:


clip_image004 clip_image006 clip_image008


Horizontal Vertical Both Horizontal and Vertical


JTable Sorting and Filtering:



  • Add sorting to your JTable with one method call:
  • setAutoCreateRowSorter(true)
  • Specify your own comparators
  • Supports secondary and tertiary sort columns
  • Can specify a filter to limit what is shown like Regular expression, number, and date implementations provided

Monitoring & Management:


Potential Problems That Can Be Detected



  • Memory leaks
  • Thread deadlocks
  • Dirty references
  • Infinite loops

Monitoring and Management



  • jps: lists JVM's
  • jconsole: can connect to applications that did not start up with the JMX agent
  • jmap: takes a detailed 'photograph' of what's going on in memory at any one point in time
  • jhat: forensic expert that will help you interpret the result of jmap
  • jstack: takes a 'photograph' of all the threads and what they are up to in their own stack frames

Compiler Access:


It opens up programmatic access to javac for in process compilation of dynamically generated Java code. It really aimed at people who create tools for Java development and for frameworks



  • Java Server Pages (JSP) or PHP construction kit engines that need to generate a bunch of classes on demand
  • Average developers will benefit indirectly from faster performing tool
  • Jasper JSP engine runs JSP TCK 3.5x faster

Pluggable Annotations


JSR 175 of JDK 5 standardized how annotations are declared in Java code but annotation processing details were relegated as an implementation detail


It allows developers to define new annotations.


@ForReview
public void myMethod ()
{
...
}
And APIs to define components that process them.
import javax.annotation.processing.*;
public class ForReviewProcessor extends AbstractProcessor
{
..
}
Integrate them with the Java Compiler
javac -processor ForReviewProcessor MyCode.java


Desktop Deployment


Java 6 helped in improving actual performance like graphics hardware acceleration on Windows and enhanced in perceived performance like true double buffering


We improved the native look & feels



  • Updated Swing Look&Feel Windows/Unix
  • LCD text rendering

Java 6 revamped Java Web Start and JRE installations



  • no more scary security dialog

Desktop – Splash Screen



  • Displays splash screen at launch
  • Support GIF, PNG, JPEG
  • Splash screen display options:
  • java -splash:SlashImage.png MyApplication
  • SplashScreen-Image manifest file option
  • Programmatic Control
  • Use java.awt.SplashScreen
  • Add progress bar, animation, etc
  • Desktop – OS Integration
  • Add app shortcut to launch bar / system tray
  • Add popup menu to system tray shortcut
  • Launch external application based on file type and the registered helper application
  • Edit / Print document based on file name /extension

Windows Look and Feel Improvements (SwingSet on Vista with 5.0)


Desktop – Swing Improvement



  • Improved Swing native look & feel
  • Still uses lightweight widget model
  • Uses native GUI engine to render widgets
  • Uses Windows XP API to rasterize components
  • Uses GTK API to render components

Swing in Java 5.


clip_image010


Swing in Java 6


\clip_image012


Security



  • Java 6 added important new APIs
  • XML Digital Signature (XMLDSig) API (JSR 105)
  • Smart Card I/O API (JSR 268)
  • Improved authentication schemes
  • JAAS-based authentication using LDAP
  • Native Platform Java GSSAPI (Generic Security
  • Services Application Programming Interface) integration

Quality, Stability, Compatibility:



  • Java 6 is still running the Big App tests
  • Java 6 now has 80,000+ JCK tests
  • Java 6 have had good uptake of weekly builds
  • Java 6 ran a Regression Challenge

5.0 Performance Improvement:


Following graph can better explain the performance enhancement along with the up gradation of different versions of Java.


clip_image014


clip_image016


ADDITIONAL LIST OF FEATURES (OR JSRs’)


This article covers the following list of features (or JSRs') that comes along with the Java 6 Platform.


A feature or an enhancement in Java is encapsulated in the form of a JSR. JSR, which stands for Java Specification Request is nothing but a formal proposal which details the need for a specific functionality to be available in the Java Platform that can be used by Applications. These JSR’s will be reviewed and released by a committee called Java Expert Groups (JEG).



  • Pluggable Annotation Processing API (JSR 269)
  • Common Annotations (JSR 250)
  • Java API for XML Based Web Services - 2.0 (JSR 224)
  • JAXB 2.0 (JSR 222)
  • Web Services Metadata (JSR 181)
  • Streaming API for XML (JSR 173)
  • XML Digital Signature (JSR 105)
  • Java Class File Specification Update (JSR 202)
  • Java Compiler API (JSR 199)
  • JDBC 4.0 (JSR 221)
  • Scripting in the Java Platform (JSR 223)

The JSRs' that are covered in this article are Common Annotations, JDBC 4.0 and Scripting in the Java Platform


Common Annotations



The aim of having Common Annotations API in the Java Platform is to avoid applications defining their own Annotations which will result in having larger number of Duplicates. This JSR is targeted to cover Annotations both in the Standard as well the Enterprise Environments. The packages that contain the annotations are javax.annotation and javax.annotation.security . Let us discuss in brief the commonly used Annotations that are available in this JSR in the next subsequent sections.


@Generated Annotation


Not all the source files or the source code in an application is hand-written by Developers. With the increasing number of Tools and Frameworks, most of the common Boiler-Plate Code is generated by the Tools or the Frameworks itself if they have been properly instructed. Such Tool Generated Code can be marked with @Generated Annotation. Consider the following sample code snippet,


MyClass.java


public class MyClass
{
public void developerCode ()
{
}
@Generated (
value = "ClassNameThatGeneratedThisCode",
comments = "This is Tool Generated Code",
date = "5 June 2007"
)
public void toolGeneratedCode ()
{
}
}


The value for the @Generated Annotation would be usually the class name that generated this code. Optionally, comments and date can be given to add more clarity to the generated code. Note this @Generated Annotation is not limited to a method definition, it can also be defined for Package Declaration, Class Declaration, Interface Declaration, Local Variable Declaration, Field Declaration, Parameter Declaration etc.


@Resource and @Resources Annotation


Any Class or Component that provides some useful functionality to an Application can be thought of as a Resource and the same can be marked with @Resource Annotation. This kind of Annotation can be seen normally in J2EE Components such as Servlets, EJB or JMS. For example consider the following code snippet,


@Resource (name = "MyQueue", type = javax.jms.Queue,
shareable = false,
authenticationType = Resource.AuthenticationType.CONTAINER,
description = "A Test Queue"
)
private javax.jms.Queue myQueue;


Queue is a class available as part of JMS API and it serves as a target for Asynchronous Messages being sent by Applications. The various properties to note in @Resource Annotation are: 'name' which is the JNDI Name of this resource, 'type' which is the type of the resource which usually points to the Fully Qualified Class Name, 'shareable' which tells whether this resource can be shared by other components in the Application or not, 'authenticationType' which indicates the type of authentication to be performed either by the Container or by the Application and the Possible values are AuthenticationType.CONTAINER and AuthenticationType.APPLICATION and 'description' which is a string that describes the purpose of this resource.


When the Application containing the @Resource Annotations are deployed to a Server, the Container will scan for all the Resource references during the time of Application loading and then will populate the @Resource References by assigning new instances.


@Resources is nothing but a collection of @Resource entries. Following is a sample code that defines @Resources Annotation,


@Resources ({
@Resource (name = "myQueue" type = javax.jms.Queue),
@Resource (name = "myTopic" type = javax.jms.Topic),
})


@PostConstruct and @PreDestroy


J2EE Components are usually created by the Container or the Framework on which they are deployed. Container creates new components by calling the


Default or the No Argument Constructor. It is a very common need that a component needs to get initialized with some default values after it has been created. @PostConstruct Annotation serves that purpose. It is a Method-Level Annotation, meaning that this Annotation can be applied only to a Method and it will be fired immediately as soon the Component is created by invoking the Constructor.


Consider the following set of code,


MyDbConnectionComponent.java


public class MyDbConnectionComponent{

public MyDbConnectionComponent(){
}

@PostConstruct()
public void loadDefaults(){

// Load the Driver Class.
// Get the Connection and Do other stuffs.

}
}


We can see that @PostConstruct Annotation is normally used to Initialize the Resources that are Context specific. The loadDefaults() method which is marked with @PostConstruct Annotation will be called immediately by the Container as soon as an instance of MyDbConnectionComponent is created. There are certain guidelines to be followed while defining the PostConstruct method such as: the method should not be marked as static, return type should be void, it cannot throw any CheckedExceptions etc.


The counterpart to @PostConstruct Annotation is the @PreDestroy Annotation. From the name of the Annotation itself, we can infer that the method that is marked with this Annotation will be called before an object is about to be removed or destroyed by the Container. Like the @PostConstruct Annotation, this is also a Method-Level Annotation and the following code snippet proves this,


MyDbConnectionComponent.java


public class MyDbConnectionComponent {

public MyDbConnectionComponent(){
}

@PreDestroy()
public void releaseResources(){

// Close the Connection.
// Unload the Class Driver from the System

}
}


The method releaseResources () will be called by the Container before the object is about to be Destroyed. Resource releasing code are ideal candidates to be placed in the @PreDestroy Annotation method.


4) Role Based Annotations


The following sections discuss the various Role-based Annotations that are very common in Applications that are very concerned about Security. A Typical Application is accessed by a wide range of Users and Users themselves fall into Several Roles. Considering an IT Organization, all Employees fall into the General Category of Roles namely Admin, Director, Manager, Engineer, Programmer etc. It is very common to see Applications following Role-Based Security Model. The Annotations @DeclareRoles, @RolesAllowed, @PermitAll, @DenyAll and @RunAs are Role-Based Annotations and are covered here.


@DeclareRoles Annotations


This is a Class-Level Annotation meaning that this Annotation is applicable only to a Class Declaration. If applied to a Class or a Component, it essentially declares the valid Set of Roles that are available for this Component. Consider the following code which will clarify this,


LeaveService.java


@DeclareRoles (value = {"Director", "Manager", "Others”})
public class LeaveService {

@Resource
private Context context;

public void applyLeave(){

// Any employee can apply for leave. So no need for any
// conditional check.
}

public void grantLeave(){
if(checkUserInRole()){
// Grant Leave.
}
}

public void cancelLeave() {
if(checkUserInRole()) {
// Cancel Leave.
}
}

private boolean checkUserInRole (){
if( (context.isCallerInRole("
Director") )
|| (context.isCallerinRole("
Manager")) ){
return true;
}

return false;
}
}


In the above example, the component LeaveService has been marked with @DeclareRoles Annotations with Role Name values namely Director and Manager. It has three services namely: applying for leave (applyLeave()), granting for leave (grantLeave()) and cancellation of leave (cancelLeave()). It is acceptable that only Employees in the Superior Role (Director or Manager) can grant or deny leaves to their sub-ordinates. So additional conditional checks are done to ensure that whether the User who is accessing the grantLeave() or the cancelLeave() service belongs to either of the defined Roles(Director or Manager). Since any employee in a company can apply for a leave, (whose Role Name is given as Others), no conditional checks are done in applyLeave() method.


@RolesAllowed Annotation


This is a Class/Method Level Annotation which is used to grant access to some Service(s) to the defined set of Users who are mentioned by their Role Names in the Annotation. Let us get into the following example straightaway,


LeaveService.java


@DeclareRoles("A", "B", "C", "X", "Y", "Z")
@RolesAllowed("A", "B", "C")
public class MyServiceComponent{

@RolesAllowed(value = {"A", "X", "Y"} )
public void myService1(){
}

@RolesAllowed(value = {"B", "Y", "Z"} )
public void myService2(){
}

@RolesAllowed(value = {"X", "Y", "Z"} )
public void myService3(){
}
public void myService4(){
}
}


The above code declares various roles namely "A", "B", "C", "X", "Y" and "Z" for the component MyServiceComponent. The @RolesAllowed Annotation when applied to a method grant Access to Users who are in that Roles only. For example, only Users with Roles "A" or "X" or "Y" are allowed to access the method myService1(). In the case of myService2(), "B", "Y" or "Z" role Users are allowed to access it and so on.


What happens in the case of myService4 ()??


No @RolesAllowed is specified for this method. The fact is that, if a method doesn’t have @RolesAllowed Annotation attached to it, then it will inherit this property from the class where it has been defined. So, in our case, Users in the Role "A", "B" or "C" can access the method myService4() because these set of Roles have been defined at the Class Level. What if the Class Declaration itself doesn’t have the @RolesAllowed Annotation declared? The answer is simple: it will take all the Roles that are defined in @DeclareRoles.


@PermitAll and @DenyAll Annotation


These are Class/Method Level Annotations and if applied to a Class Declaration will affect all the methods in the class, and when applied to a method will affect that method only.


Consider the following sample,


MyClass.java


@DeclareRoles(value = {"A", "B", "C"} )
class MyClass{

@PermitAll()
public void commonService(){
}

@DenyAll
public void confidentialService(){
}
}


From the above code, it is inferred that commonService () method can be accessible by all Users irrespective of their Roles as it is marked with @PermitAll


New Features and Performance Enhancements



Java SE 6 includes several new features and enhancements to improve performance in many areas of the platform. Improvements include: synchronization performance optimizations, compiler performance optimizations, the new Parallel Compaction Collector, better ergonomics for the Concurrent Low Pause Collector and application start-up performance.


Runtime performance optimizations


Biased locking


Biased Locking is a class of optimizations that improves uncontended synchronization performance by eliminating atomic operations associated with the Java language’s synchronization primitives. These optimizations rely on the property that not only are most monitors uncontended, they are locked by at most one thread during their lifetime.


An object is "biased" toward the thread which first acquires its monitor via a monitorenter bytecode or synchronized method invocation; subsequent monitor-related operations can be performed by that thread without using atomic operations resulting in much better performance, particularly on multiprocessor machines. Locking attempts by threads other that the one toward which the object is "biased" will cause a relatively expensive operation whereby the bias is revoked. The benefit of the elimination of atomic operations must exceed the penalty of revocation for this. Applications with substantial amounts of uncontended synchronization may attain significant speedups while others with certain patterns of locking may see slowdowns. Biased Locking is enabled by default in Java SE 6 and later. To disable Biased Locking, please add to the command line -XX:-UseBiasedLocking .


Lock coarsening


There are some patterns of locking where a lock is released and then reacquired within a piece of code where no observable operations occur in between. The lock coarsening optimization technique implemented in hotspot eliminates the unlock and relock operations in those situations (when a lock is released and then reacquired with no meaningful work done in between those operations). It basically reduces the amount of synchronization work by enlarging an existing synchronized region. Doing this around a loop could cause a lock to be held for long periods of times, so the technique is only used on non-looping control flow.


This feature is on by default. To disable it, please add the following option to the command line: -XX:-EliminateLocks


Adaptive spinning


Adaptive spinning is an optimization technique where a two-phase spin-then-block strategy is used by threads attempting a contended synchronized enter operation. This technique enables threads to avoid undesirable effects that impact performance such as context switching and repopulation of Translation Lookaside Buffers (TLBs). It is “adaptive" because the duration of the spin is determined by policy decisions based on factors such as the rate of success and/or failure of recent spin attempts on the same monitor and the state of the current lock owner.


Support for large page heap on x86 and amd64 platforms


Java SE 6 supports large page heaps on x86 and amd64 platforms. Large page heaps help the Operating System avoid costly Translation-Lookaside Buffer (TLB) misses to enable memory-intensive applications perform better (a single TLB entry can represent a larger memory range).


Please note that large page memory can sometimes negatively impact system performance. For example, when a large amount of memory is pinned by an application, it may create a shortage of regular memory and cause excessive paging in other applications and slow down the entire system. Also please note for a system that has been up for a long time, excessive fragmentation can make it impossible to reserve enough large page memory. When it happens, the OS may revert to using regular pages. Furthermore, this effect can be minimized by setting -Xms == -Xmx, -XX:PermSize == -XX:MaxPermSize and -XX:InitialCodeCacheSize == -XX:ReserverCodeCacheSize .


Another possible drawback of large pages is that the default sizes of the perm gen and code cache might be larger as a result of using a large page; this is particularly noticeable with page sizes that are larger than the default sizes for these memory areas.


Support for large pages is enabled by default on Solaris. It's off by default on Windows and Linux. Please add to the command line -XX:+UseLargePages to enable this feature. Please note that Operating System configuration changes may be required to enable large pages. For more information, please refer to the documentation on Java Support for Large Memory Pages on Sun Developer Network.


Array Copy Performance Improvements


The method instruction System.arraycopy () was further enhanced in Java SE 6. Hand-coded assembly stubs are now used for each type size when no overlap occurs.


Background Compilation in HotSpot™ Client Compiler


Prior to Java SE 6, the HotSpot Client compiler did not compile Java methods in the background by default. As a consequence, Hyperthreaded or Multi-processing systems couldn't take advantage of spare CPU cycles to optimize Java code execution speed. Background compilation is now enabled in the Java SE 6 HotSpot client compiler.


New Linear Scan Register Allocation Algorithm for the HotSpot™ Client Compiler


The HotSpot client compiler features a new linear scan register allocation algorithm that relies on static single assignment (SSA) form. This has the added advantage of providing a simplified data flow analysis and shorter live intervals which yields a better trade off between compilation time and program runtime. This new algorithm has provided performance improvements of about 10% on many internal and industry-standard.


Garbage Collection


Parallel Compaction Collector


Parallel compaction is a feature that enables the parallel collector to perform major collections in parallel resulting in lower garbage collection overhead and better application performance particularly for applications with large heaps. It is best suited to platforms with two or more processors or hardware threads. Previous to Java SE 6, while the young generation was collected in parallel, major collections were performed using a single thread. For applications with frequent major collections, this adversely affected scalability. Parallel compaction is used by default in JDK 6, but can be enabled by adding the option -XX: +UseParallelOldGC to the command line in JDK 5 update 6 and later.


Please note that parallel compaction is not available in combination with the concurrent mark sweep collector; it can only be used with the parallel young generation collector (-XX:+UseParallelGC). The documents referenced below provide more information on the available collectors and recommendations for their use. For more on the Parallel Compaction Collection, please refer to the Java SE 6 release notes. For more information on garbage collection in general, the HotSpot memory management whitepaper describes the various collectors available in HotSpot and includes recommendations on when to use parallel compaction as well as a high-level description of the algorithm.


Concurrent Low Pause Collector: Concurrent Mark Sweep Collector Enhancements


The Concurrent Mark Sweep Collector has been enhanced to provide concurrent collection for the System.gc () and Runtime.getRuntime ().gc () method instructions. Prior to Java SE 6, these methods stopped all application threads in order to collect the entire heap which sometimes resulted in lengthy pause times in applications with large heaps. In line with the goals of the Concurrent Mark Sweep Collector, this new feature is enabling the collector to keep pauses as short as possible during full heap collection. To enable this feature, add the option -XX: +ExplicitGCInvokesConcurrent to the Java command line.


The concurrent marking task in the CMS collector is now performed in parallel on platforms with multiple processors. This significantly reduces the duration of the concurrent marking cycle and enables the collector to better support applications with larger numbers of threads and high object allocation rates, particularly on large multiprocessor. Ergonomics in the 6.0 Java Virtual Machine


In Java SE 5, platform-dependent default selections for the garbage collector, heap size, and runtime compiler were introduced to better match the needs of different types of applications while requiring less command-line tuning. New tuning flags were also introduced to allow users to specify a desired behavior which in turn enabled the garbage collector to dynamically tune the size of the heap to meet the specified behavior. In Java SE 6, the default selections have been further enhanced to improve application runtime performance and garbage collector efficiency.


The chart below compares out-of-the-box SPECjbb2005™ performance between Java SE 5 and Java SE 6 Update 2. This test was conducted on a Sun Fire V890 with 24 x 1.5 GHz UltraSparc CPU's and 64 GB RAM running Solaris 10:


clip_image017


In each case the benchmarks were ran without any performance flags. Please see the SPECjbb 2005 Benchmark Disclosure


Comparison has been done on I/O performance between Java SE 5 and Java SE 6 Update 2. This test was conducted on a Sun Fire V890 with 24 x 1.5 GHz UltraSparc CPU's and 64 GB RAM running Solaris 10:


clip_image019


In each case the benchmarks were ran without any performance flags. Comparison has been done VolanoMark™ 2.5 performance between Java SE 5 and Java SE 6. VolanoMark is a pure Java benchmark that measures both (a) raw server performance and (b) server network scalability performance. In this benchmark, the client side simulates up to 4,000 concurrent socket connections. Only those VMs that successfully scale up to 4,000 connections pass the test. In both the raw performance and network scalability tests, the higher the score, the better the result.


This test was conducted on a Sun Fire V890 with 24 x 1.5 GHz UltraSparc CPU's and 64 GB RAM running Solaris 10:


clip_image020


In each case we ran the benchmark in loopback mode without any performance flags. The result shown is based upon relative throughput (messages per second with 400 loopbackconnections). Some other improvements in Java SE 6 include:



  • On server-class machines, a specified maximum pause time goal of less than or equal to 1 second will enable the Concurrent Mark Sweep Collector.
  • The garbage collector is allowed to move the boundary between the tenured generation and the young generation as needed (within prescribed limits) to better achieve performance goals. This mechanism is off by default; to activate it add this to the command line: option -XX:+UseAdaptiveGCBoundary .
  • Promotion failure handling is turned on by default for the serial (-XX: +UseSerialGC) and Parallel Young Generation (-XX:+ParNewGC) collectors. This feature allows the collector to start a minor collection and then back out of it if there is not enough space in the tenured generation to promote all the objects that need to be promoted.
  • An alternative order for copying objects from the young to the tenured generation in the parallel scavenge collector has been implemented. The intent of this feature is to decrease cache misses for objects accessed in the tenured generation. This feature is on by default. To disable it, please add this to the command line -XX:-UseDepthFirstScavengeOrder
  • The default young generation size has been increased to 1MB on x86 platforms
  • The Concurrent Mark Sweep Collector's default Young Generation size has been increased.
  • The minimum young generation size was increased from 4MB to 16MB.
  • The proportion of the overall heap used for the young generation was increased from 1/15 to 1/7.
  • The CMS collector is now using the survivor spaces by default, and their default size was increased. The primary effect of these changes is to improve application performance by reducing garbage collection overhead. However, because the default young generation size is larger, applications may also see larger young generation pause times and a larger memory footprint.

Client-side Performance Features and Improvements


New class list for Class Data Sharing


To reduce application startup time and footprint, Java SE 5.0 introduced a feature called "class data sharing" (CDS). On 32-bit platforms, this mechanism works as follows: the Sun provided installer loads a set of classes from the system jar (the jar file containing all the Java class library, called rt.jar) file into a private internal representation, and dumps that representation to a file, called a "shared archive". On subsequent JVM invocations, the shared archive is memory-mapped in, saving the cost of loading those classes and allowing much of the Java Virtual Machine's metadata for these classes to be shared among multiple JVM processes. In Java SE 6.0, the list of classes in the "shared archive" has been updated to better reflect the changes to the system jar file.


Improvements to the boot class loader


The Java Virtual Machine's boot and extension class loaders have been enhanced to improve the cold-start time of Java applications. Prior to Java SE 6, opening the system jar file caused the Java Virtual Machine to read a one-megabyte ZIP index file that translated into a lot of disk seek activity when the file was not in the disk cache. With "class data sharing" enabled, the Java Virtual Machine is now provided with a "meta-index" file (located in jre/lib) that contains high-level information about which packages (or package prefixes) are contained in which jar files. This helps the JVM avoid opening all of the jar files on the boot and extension class paths when a Java application class is loaded


Below a chart comparing application start-up time performance between Java SE 5 and Java SE 6 Update 2 is shown. This test was conducted on an Intel Core 2 Duo 2.66GHz desktop machine with 1GB of memory:


clip_image022


The application start-up comparison above shows relative performance (smaller is better) and in each case the benchmarks were ran without any performance flags.


Comparison is done on memory footprint size required between Java SE 5 and Java SE 6 Update 2. This test was conducted on an Intel Core 2 Duo 2.66GHz desktop machine with 1GB of memory:


clip_image024


The footprint comparison above shows relative performance (smaller is better) and in each case the benchmarks were run without any performance flags.


Despite the addition of many new features, the Java Virtual Machine's core memory usage has been pared down to make the actual memory impact on your system even lower than with Java SE 5


Splash Screen Functionality


Java SE 6 provides a solution that allows an application to show a splash screen before the virtual machine starts. Now, a Java application launcher is able to decode an image and display it in a simple non-decorated window.


Swing's true double buffering


Swing's true double buffering has now been enabled. Swing used to provide double buffering on an application basis, it now provides it on a per-window basis and native exposed events are copied directly from the double buffer. This significantly improves Swing performance, especially on remote servers.


Improving rendering on windows systems


The UxTheme API, which allows standard Look&Feel rendering of windows controls on Microsoft Windows systems, has been adopted to improve the fidelity of Swing Systems Look & Feels.




New Platform Support



Windows Vista


Java SE 6 is supported on Windows Vista Ultimate Edition, Home Premium Edition, Home Basic Edition, Enterprise Edition and Business Edition in addition to Windows XP Home and Professional, 2000 Professional, 2000 Server, and 2003 Server.


Benchmark Disclosure


SPECjbb 2005


SPECjbb2000 is a benchmark from the Standard Performance Evaluation Corporation. The performance referenced is based on Sun internal software testing conforming to the testing methodologies listed above.


VolanoMark™ 2.5


VolanoMark™ version 2.5 is a benchmark from Volano




Why should one upgrade to Java 6?


There are several enhancements that we have added in the latest release of the Java Runtime Environment 6 (JRE 6).



  • Improved performance and stability.
  • Better compatibility with previous releases of the JRE.
  • Important bug fixes have been added.
  • Applications gain improved look and feel.
  • Full support for Windows Vista.
  • Rapid access to critical fixes & updates, with auto-update.

MORE TECHNICAL INFORMATION Some of the other enhancements that are incorporated in JRE 6 release are as follows: Cache and System Format The caching mechanism has been upgraded. Existing applications in the Java Web Start cache will be upgraded and converted to the new cache format the first time you run a Java Web Start application Download Engine and Cache Consolidation The caching mechanism and download engine are redesigned and consolidated between Java Web Start and Java Plug-in. This brings several new features to Java Web Start, previously available only in Java Plug-in and vice versa. They are:



  • Caching can be disabled using the Java Control Panel.
  • Java Web Start honors the maximum cache size set using Java Control Panel.
  • Java Web Start can start a cleanup thread to remove Least Recently Used (LRU) items from the cache when approaching the maximum cache size.
  • The no-cache directive is now supported. When the no-cache directive is used, an update check is made to make sure the cached contents are same as at the URL. The resource is then downloaded into the cache and the expiration field is ignored.
  • The expiration-date is supported. If a downloaded resource contains an expiration date, it will not be used after that date.

Secure Versioning In JRE 6 unsigned Java Web Start applications that specify a version other than the current one will trigger a security warning, requiring explicit user permission before the application will run. Signed Java Web Start applications are not affected. Other Enhancements


Java Web Start and Java Plug-in now support CRL (Certificate Revocation Lists) and OCSP (Online Certificate Status Protocol) for verifying the certificates.


Java Control Panel provides an option to select the default SSL handshaking protocol. The default is set to SSLv3 and SSLv2. You can also change it to TSL.


The Java Console is excluded from modality. By using the new modality features of AWT in JRE 6, you can interact with Java Console even when your application is displaying a modal dialog.


All dialogs and screens of Java Web Start and Java Plug-in are redesigned to be more user friendly, intuitive, and accessible


Java 6 Update 10 (6u10)


It is a release that introduces new features and enhancements aimed at providing an optimized consumer-end user experience. Java 6u10 focuses on the following areas: Enhanced Deployment


The Java Deployment Toolkit takes the guess work out of determining what versions of the Java Platform end users have installed on their PCs. It supplies Java-based web applet/application deployment with a simple JavaScript interface. This greatly increases the ease of detection of users' Java environment, as well as the ease of Java Platform deployment. New Online Installer


The Java Kernel online installer lets first time Java users run applets and Java Web Start applications quicker without waiting for the whole Java Platform to be downloaded. The Kernel installation is expected to satisfy the requirements of most Java applets and applications, and any additional libraries that may be required at runtime are downloaded to complete the Java Kernel installation. This installation mechanism lets the end user get up and running significantly faster, while the complete Java Platform installation takes place in the background


Enhanced Auto update


The Java auto update mechanism has also been improved, using a patch-in-place mechanism that translates in a faster and more reliable update process (the patch in place mechanism will take effect for end users, starting with Java 6u10, updating to a later update release). Future update releases will install the existing release, removing the previous release. Each update release will no longer be listed as separate items in the Windows 'Add or Remove Programs' dialog and will no longer consume additional disk space.


Improved performance


The Java Quick Starter feature will prefetch portions of Java into memory, substantially decreasing the average cold start-up time (the time that it takes to launch a Java application for the first time after a fresh reboot of a PC). For more information, please visit Java Quick Starter Hardware acceleration support


New hardware accelerated graphics pipeline based on the Microsoft Direct3D 9 API, translate into improved rendering of Swing applications which rely on translucency, gradients, arbitrary transformations, and other more advanced 2D operations. A new cross-platform Swing look and feel, code name Nimbus, provides a nice update over 'Metal' and 'Ocean' and with exciting features. Next-Generation Java Plug-In


Java 6u10 includes a brand-new implementation of the Java Plug-in, which is used by default as long as you are using Firefox 3 or Internet Explorer. The next-generation plug-in runs applets outside of the browser in one or more separate processes. Applets still appear inside of the web browser window as they always have, but this means that it is now possible to use different Java versions, command-line arguments, and configurations to run different applets. The isolation provided by running the web browser and the Java -- two very large, very complex pieces of software -- in separate process spaces improves the reliability of both, and gives applets the same flexibility and control over configurations that other Java software has always enjoyed. For more information on switching between Old Classic plug-in and Next generation plug-in, please visit Switch between old and new plug-in.


Tabulation on Enhancements of Java 4, Java 5 and Java 6.


Java 4.0 Java 5.0 Java 6
Assert keyword Generics: Provides compile-time (static) type safety for collections and eliminates the need for most typecasts (type conversion). Java Deployment Toolkit, a set of JavaScript functions to ease the deployment of applets and Java Web Start applications
Regular expressions modeled after Perl regular expressions Metadata: Also called annotations; allows language constructs such as classes and methods to be tagged with additional data, which can then be processed by metadata-aware utilities. Java Kernel, a small installer including only the most commonly used JRE classes. Other packages are downloaded when needed
exception chaining allows an exception to encapsulate original lower-level exception Autoboxing/unboxing: Automatic conversions between primitive types (such as int) and primitive wrapper classes (such as Integer). Enhanced updater
Internet Protocol version 6 (IPv6) support non-blocking NIO (New Input/Output) Enumerations: The enum keyword creates a typesafe, ordered list of values (such as Day.MONDAY, Day.TUESDAY, etc.). Previously this could only be achieved by non-typesafe constant integers or manually constructed classes (typesafe enum pattern). Enhanced versioning and pack200 support: server-side support is no longer required.
Logging API Varargs: The last parameter of a method can now be declared using a type name followed by three dots (e.g. void drawtext(String... lines)). In the calling code any number of parameters of that type can be used and they are then placed in an array to be passed to the method, or alternatively the calling code can pass an array of that type. Java Quick Starter, to improve cold start-up time
Image I/O API for reading and writing images in formats like JPEG and PNG Enhanced for each loop: The for loop syntax is extended with special syntax for iterating over each member of either an array or any Iterable, such as the standard Collection classes, using a construct of the form Improved performance of Java2D graphics primitives on Windows, using Direct3D and hardware acceleration.
Integrated XML parser and XSLT processor (JAXP) Swing: New skinnable look and feel, called synth. A new Swing look and feel called Nimbus and based on synth
Integrated security and cryptography extensions static imports Next-Generation Java Plug-In: applets now run in a separate process and support many features of Web Start applications.
Java Web Start included Scanner class for parsing data from various input streams and buffers.  


Reference



 


Related Posts


0 comments:

Text Widget

Copyright © Vinay's Blog | Powered by Blogger

Design by | Blogger Theme by