Java
JDKTM6 Adoption Guide

Revision 1.0.8
JDK Documentation Contents

Table of Contents



1 Purpose
1.1 Purpose of this Document
1.2 How this Document is Structured
2 Development Time Migration Issues
2.1 API Behaviors
2.1.1 Runtime Behaviors
2.1.2 JVM TI
2.1.3 Swing
2.1.4 AWT
2.1.5 I18N
2.1.6 Java Sound
2.1.7 Beans
2.1.8 JMX
2.1.9 Networking
2.2 Source Incompatibilities
2.2.1 JMX
2.2.2 JVM TI
2.2.3 Java Compiler
2.3 Dependencies on Implementation Mechanisms
2.3.1 Runtime Dependencies
2.3.2 AWT
2.3.3 Java 2D
2.3.4 Beans
2.3.5 JVM TI
2.4 Deprecated APIs
2.4.1 JMX
2.4.2 JVM TI
2.5 Reserved Keywords
2.5.1 JMX
2.6 New Features or APIs of Note During Migration
2.6.1 Runtime
2.6.2 Monitoring and Management
2.6.3 JDI and JDWP
2.6.4 Swing
2.6.5 AWT
2.6.6 I18N
2.6.7 Beans
2.6.8 JMX
2.6.9 Java 2D
2.6.10 Core Libraries
2.6.11 Networking
2.6.12 Java Compiler
3 Deployment and Configuration Issues
3.1 New or Changed Configuration Properties
3.1.1 Monitoring and Management
3.1.2 Swing
3.1.3 Core Libraries
3.2 New Command Line Tool Arguments
3.2.1 AWT
3.2.2 New VM Command Line Options
3.2.3 Monitoring and Management
3.2.4 Java Compiler
3.2.5 Core Libraries
3.3 New Developer Tools that Replace Old Ones
3.3.1 Monitoring and Management
3.3.2 Annotation Processing
3.4 Changed Developer Tool Defaults/Behaviors
3.4.1 JDI and JDWP
3.4.2 Annotation Processing
3.5 Newly Supported Platform Behaviors
3.5.1 Swing
3.6 Other
3.6.1 Networking
3.6.2 Deployment
4 Tools and Platform Developer Issues
4.1 Class File Format Changes
4.1.1 JSR 202 Classfile Changes
4.1.2 Java Compiler
4.2 Deprecation of any Tool-specific or com.sun.* APIs

1 Purpose

The JDK 6 adoption guide is intended as an aid to the IT professional who is planning to upgrade from an existing deployment of J2SE 1.5 to JDK 6.

1.1 Purpose of this Document

 
 

The new API features in JDK 6, as with all releases, have been carefully designed in the Java Community Process to ensure backward binary API compatibility. That is to say, applications that depend on APIs that exist in a previous version of Java SE will continue to work exactly as they do today. In finalizing JDK 6, Sun has spent many thousands of man hours testing, with the help of some well-known software applications, so that this goal is achieved.

However there are a number of different kinds of changes in each Java SE platform implementation that may require attention when upgrading. Prior knowledge of these issues, each of which may be small, is essential in planning for a smooth upgrade in order to take advantage of the many improvements in Java SE for this version.

Examples of such issues include changes to APIs that are not formally part of the platform, but that are available in Sun's implementation. They may include changes or enhancements to file formats that are not specified as part of the platform. They may include fixing of bugs in platform behavior in corner cases where the implementation did not follow the specification, or where the specification has been clarified to remove ambiguity. They may include changes to configuration parameters, or command line options to the tools that ship with Sun's JDK. In each case, the IT professional may need to plan to make a change to applications deployed, or to the deployment of the Java platform.

This document intends to be a complete listing of all such issues, together with the effect each issue may have on a deployment and with a remedy.

We expect that there will be many IT professionals who have deployed a collection of applications on J2SE 1.5 and who will read this document to discover that none of the issues affect their deployment should they choose to upgrade. In understanding the totality of these issues, the IT professional will be able to plan ahead of time to address any issues in their deployment that will require attention in order to achieve a smooth upgrade from J2SE 1.5 to Java SE 6.

1.2 How this Document is Structured

 
 

As an aid to planning for upgrading to Java SE 6, this document is divided into three areas. The first section focuses on issues that may require adjustment by a Java Developer to the source code or configuration of applications currently deployed. The second section catalogs the issues the System Administrator may need to plan for in order to ensure the smooth deployment of applications on the upgraded Java SE platform. The final section covers changes to features of the Java SE platform that developers of tools may depend on, such as the class file format.

2 Development Time Migration Issues

This section of the adoption guide is aimed at Java Developers who have created applications that are running on J2SE 1.5 and who are considering upgrading the underlying platform to Java SE 6. This section lists all the issues that may potentially affect their applications, provides a description of the likely effect on their applications if they take no action, and provides a suggested remedy.

2.1 API Behaviors

 
 

This section contains all the corner case changes where an API may have changed behavior. While maintaining backwards binary compatibility is a primary driver for each Java SE release, there are corner cases where the original API behavior was not clear, and where in clarifying it, some applications may be affected. Affected applications will continue to compile under Java SE 6, but there may be differences in runtime behavior.

2.1.1.Runtime Behaviors

 
 

JNI specification clarifications

Description
JNI: DetachCurrentThread should release thread-owned monitors. The JNI DetachCurrentThread specification states that Java monitors held by the thread are released when the thread is detached. Before this fix, the Hotspot VM did not release these monitors. Since Java SE 6.0, a JNI DetachCurrentThread operation will release Java monitors owned by that thread, as stated in the JNI specification. However, it is possible to turn off this behavior and revert to the old behavior by specifying -XX:-JNIDetachReleasesMonitors to the Java VM.

Consequence Without Action
Likely none. This behavior change should only affect applications that relied on the buggy behavior that detaching threads might hold onto some monitors. In practice, it should be very rare that an application is affected by this change.

Recommended Fix
The preferred fix is to modify your application to conform to the JNI specification, i.e., that detaching a thread releases monitors held by the thread. Otherwise, the VM option
-XX:-JNIDetachReleasesMonitors may be specified on the command line to revert to the pre-JDK 6 behavior.

Further Reading


2.1.2 JVM TI

 
 

GetVersionNumber returns 1.1.

Description
This is a new version of JVM TI

Consequence Without Action
None, unless the caller does not allow for this value

Recommended Fix
None, unless the caller does not allow for this value

Further Reading


Specify that static field indices are defined the same as instance field indices.

Description
This was needed for some of the heap walking functionality

Consequence Without Action
None

Recommended Fix
None

Further Reading


In GetThreadListStackTraces, add JVMTI_ERROR_INVALID_THREAD error to cover an invalid thread in the list.

Description
None of the universal errors cover this case

Consequence Without Action
None

Recommended Fix
Could check for this error and give a more meaningful error message

Further Reading


Disallow NULL for the heap_object_callback parameter of IterateOverHeap and IterateOverInstancesOfClass functions.

Description
Made spec match behavior

Consequence Without Action
None

Recommended Fix
None

Further Reading


Change IsMethodObsolete to no longer require the can_redefine_classes capability.

Description
An additional way of modifying classes was introduced, see RetransformClasses below, which has its own capabilities. Rather than adding more capabilities needed for IsMethodObsolete, it made more sense to just remove the need for any capability. IsMethodObsolete is meaningful even if no redefine or retransform capabilities exist ; it will just always return false.

Consequence Without Action
None

Recommended Fix
None

Further Reading


In GetStackTrace, no test is done for start_depth too big if start_depth is zero.

Description
For an empty stack (stackDepth ==0), it is impossible to query the stack trace.

Consequence Without Action
None

Recommended Fix
None

Further Reading


Specification Changes/Clarifications

 
 

Clarify, correct and make consistent: wording about current thread, opaque frames and insufficient number of frames in PopFrame.

Description
These issues were not clear

Consequence Without Action
None

Recommended Fix
None

Further Reading


Clarify the JVMTI_ERROR_TYPE_MISMATCH errors in GetLocal* and SetLocal* by making them compatible with those in ForceEarlyReturn*.

Description

The definitions of mismatches were not accurate.

Consequence Without Action
None

Recommended Fix
None

Further Reading


Clarify that exception events cover all Throwables.

Description
It was not clear that all Throwables are reported.

Consequence Without Action
None

Recommended Fix
None

Further Reading


In GetThreadListStackTraces, specify that unstarted threads return empty stacks.

Description
An oversight in the spec

Consequence Without Action
None

Recommended Fix
None

Further Reading


Clarify that exactly one Agent_OnLoad (or Agent_OnAttach) is called per agent.

Description
It was not clear that this happened, for example if foo is loaded via the command line and later via attach

Consequence Without Action
None

Recommended Fix
None

Further Reading


Clarify that JVM TI functions never throw exceptions and that exception state is preserved across JVM TI function calls.

Description
It was not clear that this was the case.

Consequence Without Action
None

Recommended Fix
If an agent was set up to allow for exceptions, it could be simplified.

Further Reading


Clarify the heap_object_callback parameter of IterateOverHeap and IterateOverInstancesOfClass functions.

Description
The spec contained an incorrect definition of this parameter.

Consequence Without Action
None

Recommended Fix
None

Further Reading


Clarify that IterateOverInstancesOfClass includes subclasses.

Description
The spec did not state this

Consequence Without Action
None

Recommended Fix
Be sure agents are coded to expect this.

Further Reading


Clarify the timing of the MonitorWait and MonitorWaited events.

Description
The spec was not clear on when these events would be generated

Consequence Without Action
None

Recommended Fix
None, just be aware of the new wording

Further Reading


Clarify the SetJNIFunctionTable will only be effective after re-fetch of the table.

Description
A compiler could generate code that does not re-fetch from the the table, thus making the changes be not used.

Consequence Without Action
None

Recommended Fix
None

Further Reading


Clarify that memory allocated by JVM TI must be freed by JVM TI and vice versa.

Description
Mixing allocates/frees will not work

Consequence Without Action
None

Recommended Fix
None

Further Reading


2.1.3 Swing

 

Better Swing threading model documentation

Description
Swing has now clearly documented its threading model, including the fact that all GUIs need to be constructed on the Event-Dispatch Thread. New documentation exists in the package level doc for Swing and in the class level doc for JComponent.java.

Consequence Without Action
Accessing Swing from outside the Event Dispatch Thread might lead to unexpected results, throwing strange exceptions, visual artifacts, wrong state of Swing components, etc.

Recommended Fix
Creation and use of Swing components must be performed on the Event Dispatch Thread only.

Further Reading


Corrections to how JTabbedPane fires state changes

Description
There were certain cases where JTabbedPane did not fire stateChange events, and cases where tab selection went to the wrong place. For example, deleting a tab before the selection caused selection to move to the next tab (same index) and no event to be fired. Instead, selection should have stayed on the same tab, with an event being fired to indicate that the index has changed. JTabbedPane selection in the face of additions/removals has been revised. There is potential for this to impact code that worked around the old behavior.

Consequence Without Action
If a custom workaround is used, in certain cases a wrong tab might be selected after deleting another tab.

Recommended Fix
Remove custom workarounds for this problem.

Further Reading


JDialog support for true parent-less modeDescription of issue and background

Description
Previously, Swing used a hidden shared frame as an owner for all parentless JDialogs. With AWT now allowing true parentless Dialogs, Swing needed to allow the creation of true parentless JDialogs. The API was changed such that you can now create a parentless JDialog with passing null to a constructor of JDialog which accepts Window or Dialog as the dialog's owner, e.g., JDialog(Window) or JDialog(Dialog). Also, a createDialog(String) method was added to JOptionPane to allow creating parentless JOptionPanes.

Consequence Without Action
None. But you should be aware that null became a valid value for JDialog's owner and check it in your future JDK 6 projects.

Recommended Fix
It is not necessary to change anything because null was an invalid value for JDialog's owner before.

Further Reading


Drag gesture in Java was different from Windows

Description
In the previous Swing implementation of Drag and Drop, users were required to first click on an item to select it and then press again on the same item before they could begin a drag operation. This was annoying to users who are more familiar with using a single press to both change selection and start a drag. Swing needed to be consistent with this model, of which Windows is the best example. The implementation of drag gesture recognition in Swing was changed to the single press drag model, and the documentation was updated for the affected components to describe how drag gestures are recognized.

Consequence Without Action
None

Recommended Fix
No updates to existing code are required.

Further Reading


Using Ctrl-Shift-Clicking to create disjoint selection intervals

Description
JTable, JList, and JTree did not previously support the CTRL-SHIFT-CLICK paradigm (like Microsoft Windows) for creating disjoint selections. For tree and list, the problem was easily solved by changes to the private implementation in the UI classes. JTable, on the other hand, deals with selection changes by way of the JTable.changeSelection() method. JTable.changeSelection() takes a set of boolean parameters (toggle and extend) that determine how it changes the selection. The combination true/true for these parameters will have the method do the CTRL-SHIFT-CLICK behavior. Previously, this parameter combination was documented to do something else that may have been meaningful in the 1.4 timeframe but is now useless. Internally we do not call the method with true/true and do not expect many others to do so. Therefore, we changed the method to handle the CTRL-SHIFT-CLICK behavior on true/true and now call it with that combination when appropriate.

Consequence Without Action
None

Recommended Fix
No updates to existing code are required

Further Reading


Better documentation for JDialog.setDefaultCloseOperation()

Description
javax.swing.JDialog.setDefaultCloseOperation() was identified as having poor documentation in compared to its counterpart in javax.swing.JFrame.setDefaultCloseOperation(). The documentation needed to be fixed. In addition, the JDialog version didn't fire a property change and throw an IllegalArgumentException like its JFrame counterpart. The documentation was updated to be much clearer. A property change event is now fired, like for JFrame, and the method will now throw an IllegalArgumentException for bad arguments, including JFrame.EXIT_ON_CLOSE which previously resulted in no action..

Consequence Without Action
IllegalArgumentException can be thrown if your code passes an invalid value to setDefaultCloseOperation.

Recommended Fix
Ensure any calls to setDefaultCloseOperation on JDialog use one of the valid values. This does not include JFrame.EXIT_ON_CLOSE.

Further Reading


Specifying constraints on SpringLayout was order dependent

Description
SpringLayout allows developers to specify three Springs along each axis that dictate the size and position of a component. Only two Springs are needed along each axis, with the third being derived. When the developer specifies three springs, the layout is considered overly constrained and one of the springs must be dropped. The previous behavior for determining which spring to drop was non-intuitive and lead to ordering problems. SpringLayout now maintains the order in which springs have been set. As a result, specifying springs is no longer order dependent. In addition, support for centering, and aligning along the baseline has been added.

Consequence Without Action
If your code relies on SpringLayout to constrain ordering, it might cause an incorrect layout in JDK 6.

Recommended Fix
Update existing code to remove dependencies on SpringLayout constraint ordering

Further Reading


2.1.4 AWT

 

Minimum size for java.awt.Frame is now being enforced.

Description
The method Window.setMinimumSize() has been modified to restrict user-resizing of top-level windows to below specified dimensions. Previously, the minimum size set for top-level windows was ignored by the platform, so this change can impact code that uses the minimumSize property of top-level windows for its own needs.

Consequence Without Action
If, in the application, a minimum size is explicitly set for a top-level window then a user or developer will not be able to resize it to a smaller size.

Recommended Fix
Either stop setting a minimum size for top-level windows or reset it when it is required by an application's logic.

Further Reading


XToolkit has been made the default toolkit on Solaris

Description
XAWT is the new AWT toolkit introduced in J2SE 1.5. Its implementation is purely Java with only minimal wrappers to native functions. It is simpler, faster, and easier to maintain. It is more compatible with the latest desktop systems (Gnome, KDE, Cinnabar) and latest protocols (_NET, XEmbed). It is safer and more flexible as it is pure Java. It is also backward-compatible to the Motif toolkit.

Consequence Without Action
XToolkit will be use as the default toolkit for Solaris

Recommended Fix
If you need to use MToolkit you need to set the AWT_TOOLKIT environment variable to MToolkit

Further Reading


Changes in event firing

Description
Multiple problems in event firing were fixed: fallacious and duplicate events removed, missing events added, platform inconsistencies fixed. There is potential for this to impact code that worked around the old behavior. See the bug reports for more details.

Consequence Without Action
In some cases an application will not receive the same number of events as before. This may cause problems for that application which either try to workaround fixed problems or depend on the number of events.

Recommended Fix
Remove workarounds for the fixed problems.

Further Reading


Changes in focus handling

Description
Multiple problems in focus handling were fixed, especially with non-focusable windows and platform inconsistencies. This may impact workarounds for old behavior. See the bug reports for more details.

Consequence Without Action
Workarounds for the fixed problems may cause problems for the application which contains them.

Recommended Fix
Remove workarounds for the fixed problems.

Further Reading


2.1.5 I18N

 

Returned name from java.util.TimeZone.getDisplayName(boolean, int, java.util.Locale)

Description
java.util.TimeZone.getDisplayName(boolean, int, java.util.Locale) no longer takes the java.util.TimeZone.useDaylightTime() value into account when the daylight saving time name is requested so that java.util.getDisplayName(boolean, int, java.util.Locale) returns daylight saving time names correctly.

Consequence Without Action
java.util.TimeZone.getDisplayName(boolean, int, java.util.Locale) returns the daylight saving time name (if it ever existed) even if java.util.TimeZone.useDaylightTime() returns 'false'.

Recommended Fix

None

Further Reading


java.text.Collator.getInstance() change

Description
java.text.Collator.getInstance() does not always return a java.text.RuleBasedCollator instance. The java.text.RuleBasedCollator documentation has been updated.

Consequence Without Action
If an application assumes the returned instance is a RuleBasedCollator instance, a ClassCastException or NoSuchMethodException may be thrown, depending on how the application deals with the returned instance.

Recommended Fix
If the application tries to issue a RuleBasedCollator instance specific method, do so after checking it with 'instanceof' condition.

Further Reading


java.text.BreakIterator changes

Description
java.text.BreakIterator.preceding(int) and java.text.BreakIterator.isBoundary(int) accept the last boundary of the text which is returned from java.text.BreakIterator.last(). Previously, these methods threw an IllegalArgumentException with the last text boundary.

Consequence Without Action
IllegalArgumentException will not be thrown in preceding() or isBoundary() methods with the last boundary as a parameter.

Recommended Fix
None

Further Reading


Locale sensitive services no longer fall back to the default locale

Description
The locale sensitive classes in the java.text and java.util packages, such as java.text.DateFormat, no longer fall back to the default java.util.Locale when any locale sensitive service for the given java.util.Locale is not found. The fallback to the default java.util.Locale is often seen as a confusion rather than as a convenience.

Consequence Without Action
Fallback to the default locale will not take place

Recommended Fix
None

Further Reading


2.1.6 Javasound

 

Synthesizer.remapInstrument method's behavior has been changed

Description
The behavior of method Synthesizer.remapInstrument was not fully defined. There was no ability for the Synthesizer implementation to avoid instrument remapping support. Instrument remapping is very rarely used.The Synthesizer.remapInstrument implementation did not work.

Due the change, behavior of the remapInstrument method of the Synthesizer interface has been changed:

The JavaSound synthesizer implementation has been changed accordingly.

Consequence Without Action
Likely none.

Existing code which uses the Synthesizer interface as a client will handle successful results as success, and failure (either "false" result or IllegalArgumentException) as failure.

Existing code which implements the Synthesizer interface will not satisfy the spec, but in most cases old behavior will be handled correctly.

Recommended Fix
In client applications, review failure handling in Synthesizer.remapInstrument. In Synthesizer interface implementations, change failure notification to satisfy the spec.

Further Reading


2.1.7 Beans

 

Better EventHandler documentation and argument checking

Description
The documentation for java.beans.EventHandler had two problems. Previously it did not completely describe what the eventPropertyName argument does, and it did not document what the behavior was for invalid arguments. The documentation has been enhanced to describe clearly the eventPropertyName argument, and the create() methods and the constructor have been modified to throw NullPointerException for null arguments.

Consequence Without Action
None

Recommended Fix
No updates to existing code are required.

Further Reading


2.1.8 JMX

 

Better support for schema evolution in CompositeData and CompositeType

Description
The semantics of CompositeType.isValue have changed slightly. It will accept a CompositeData that has all the items in the CompositeType, plus some extra items. Previously, extra items were not allowed.

Consequence Without Action
Note that such a CompositeData will work correctly with code that expects just the items listed in the CompositeType.

Recommended Fix
No updates to existing code are required.

Further Reading


MBeanServerInvocationHandler no longer forwards Object methods to MBean

Description
An MBean proxy created with MBeanServerInvocationHandler.newProxyInstance will no longer forward the methods toString(), hashCode(), and equals(Object) to the remote MBean, unless they are explicitly mentioned in the MBean interface of the proxy.

Consequence Without Action
Existing code could break if either

Recommended Fix
Any existing code that relied on the methods being forwarded (and typically getting an exception from the remote MBean) will need to be changed.

Further Reading


javax.management.timer.Timer.getNotificationIDs returned wrong kind of Vector

Description
The method Timer.getNotificationIDs(String type) is specified to return a Vector of Integer objects. But the implementation previously returned a Vector of TimerNotification objects.

Consequence Without Action
Existing code calling this method could get a ClassCastException.

Recommended Fix
Any code that calls this specialized method will need to be changed to adjust to this correction, i.e., the code will have to cast to Vector instead of Vector.

Further Reading


NotificationBroadcasterSupport behavior changed when a NotificationFilter throws an exception

Description
When NotificationBroadcasterSupport is sending a Notification to a set of listeners, and the NotificationFilter associated with one of those listeners throws a RuntimeException, previously the notification dispatch stopped at that point. Now it continues with the other listeners.

Consequence Without Action
Some listeners that were not notified before will be notified now.

Recommended Fix
Code that depended on the previous behavior will need to be changed.

Further Reading


javax.management.Descriptor interface defines equals and hashCode

Description

The class DescriptorSupport now implements equals and hashCode such that two instances are equal if they have the same contents. Previously it inherited the default behaviour of these methods from Object, so two instances were equal only if they were identical.

Consequence Without Action
The equals method call for two instances of DescriptorSupport that previously returned 'false' because they were not identical may now return 'true' because they have the same contents.

Recommended Fix
Code that depended on the previous behavior will need to be changed to use '==' instead of the equals method.

Further Reading


JMX Descriptor.getFieldValues spec was broken when descriptor empty

Description
The class DescriptorSupport previously interpreted some text in the Descriptor spec literally, such that an empty Descriptor would always return an empty array from getFieldValues(stringArray), rather than an array of stringArray.length values (possibly null) as for any non-empty Descriptor. The previously specified behavior was likely to result in an unexpected ArrayIndexOutOfBoundsException in cases that were not tested where empty Descriptors arise.

Consequence Without Action
Existing code that relied on the previously specified behavior will now result in a non-empty array with stringArray.length values (possibly null) instead of an empty stringArray.

Recommended Fix
It is very unlikely that any existing code relied on this behavior, but if so then it will need to be changed to handle the returned stringArray with stringArray.length values that are possibly null.

Further Reading


Allow UNKNOWN as impact value for OpenMBeanOperationInfo

Description
The result of OpenMBeanOperationInfoSupport.getImpact() can now be MBeanOperationInfo.UNKNOWN, consistent with other types of MBeans.

Consequence Without Action
if-then-else or switch-case clauses in existing code handling Open MBeans may skip the UNKNOWN impact (because it was not a valid value before) and fail unexpectedly.

Recommended Fix
Code that relied on this not being possible will have to be changed to handle the UNKNOWN impact value.

Further Reading


Query.{initial|any|final}SubString no longer interprets wildcards

Description
The methods initialSubString, anySubString, and finalSubString in javax.management.Query previously allowed the substring in question to contain wildcards. For example, Query.initialSubString(Query.attr("X"), "a*b") would return true if the value of the X attribute was "acrobat".

However, the specification did not mention any wildcard interpretation, so the implementation has been changed to treat the string as a literal string. Therefore, the above query will only match if the value of X begins with the exact three characters "a*b".

Consequence Without Action
Existing queries relying on the '*' and '?' characters being considered as wildcards in initialSubString, anySubString, and finalSubString that used to evaluate to true will now evaluate to false.

Recommended Fix
To perform a wildcard match, add an extra * at the end for initialSubString, at the beginning for finalSubString, and at both ends for anySubString. For example, Query.match(Query.attr("X"), "a*b*").

Further Reading


Attribute type check was too restrictive in RequiredModelMBean.getAttribute

Description
RequiredModelMBean.getAttribute previously required the returned value to be an instance of the exact class mentioned in the ModelMBeanAttributeInfo, throwing an exception if not. This has been changed so that it can also be an instance of any subclass.

Consequence Without Action
Existing code will no longer get the exception javax.management.InvalidAttributeValueException for the case where the declared type is an interface or a concrete class and the return value's type is an implementation of the interface or a subclass of the existing class.

Recommended Fix
Code that relied on the previous behavior will need to be changed to handle the returned attribute's value instead of the no longer thrown exception javax.management.InvalidAttributeValueException.

Further Reading


RequiredModelMBean.setAttribute throws exception if no setMethod

Description
An application will see a change in behavior only if it defines a getMethod but not a setMethod for an attribute, but nevertheless attempts to set the attribute. Previously this set succeeded even though it had no effect, whereas now it will get an exception.

Consequence Without Action
There is a small risk that an existing application may depend on the previous silent failure, which must be balanced against the improved error detection from following the specification. Existing code will now get an exception for which a throws clause may not be expected, causing the application to fail unexpectedly.

Recommended Fix
Code that relies on the previous behaviour will need to be changed in order to handle the exception.

Further Reading


JMX API no longer creates one thread per Monitor

Description
Previously, every Monitor (GaugeMonitor, CounterMonitor, or StringMonitor) had its own thread. The Monitor's calls to MBeanServer.getAttribute to retrieve the value being monitored took place in that thread. Now, all Monitors share the same thread pool, with a default size of 10 threads. This pool is adjustable with the system property jmx.x.monitor.maximum.pool.size.

Consequence Without Action
Performance might be degraded if the number of monitors being used is very big compared to the number of threads in the thread pool (by default 10 threads maximum at a given time).

Recommended Fix
Code that depends on the previous behavior (i.e., that getAttribute would always be called from the same thread for a given Monitor) will need to be changed.

Further Reading


Monitor service supports complex types

Description
With the Monitor service, javax.management.monitor, you could previously only monitor an attribute of simple type. Often, the value you want to monitor is inside a more complex type. The value being monitored can now be a simple value contained within a complex type. For example, the MemoryMXBean defined in java.lang.management has an attribute HeapMemoryUsage of type MemoryUsage. To monitor the amount of used memory as described by the used property of MemoryUsage, you could monitor HeapMemoryUsage.used. The string HeapMemoryUsage.used would be the argument to Monitor.setObservedAttribute.

Consequence Without Action
A string of the form a.b now has a special meaning in the Monitor service. This will only affect existing code if it monitored an attribute whose name contained a dot (like a.b) and that attribute was not declared in the MBean's MBeanInfo.

Recommended Fix
Declare the a.b attribute in the MBean's MBeanInfo such that the new implementation sees it as the name of a simple type attribute instead of the dot notation name of a complex attribute.

Further Reading


Open MBeans support arrays of primitive types

Description
The set of types that can be referenced by an Open MBean is by design limited. It includes the primitive wrapper types such as java.lang.Integer and java.lang.Boolean, but does not include the primitive types such as int and boolean. When the type is Integer or Boolean there is no great difference to a client, because reflection treats this the same as int or boolean. However, when it is Integer[] or Boolean[] it is inconvenient and inefficient. All we are really interested in is arrays of primitive types. There is no difference between int and Integer when they are the type of an attribute, parameter, or return value. An int will be wrapped as an Integer anyway since everything is happening through reflection. On the other hand, there is a difference between int[] and Integer[]. int[] is considerably more efficient in space and time, but is not currently expressible as an OpenType. So the idea here has been to extend ArrayType rather than SimpleType such that you can describe int[], etc. with it.

Consequence Without Action
The following interoperability issue may arise when a client running J2SE 1.5 is connected using the JMX Remote API to a server running Java SE 6, or vice versa. An array in an Open MBean can now have a primitive element type like int[]. A J2SE 1.5 client will not see this in the corresponding ArrayType, so it will see Integer[] instead of int[]. This may cause it to misbehave. Because previous versions of the API lack the new primitiveArray boolean field, they will deserialize an int[] as an Integer[]. This will often work (for example if arrays are read using java.lang.reflect.Array) but will occasionally cause ClassCastExceptions. This only applies to "generic" (model-neutral) clients, since models that use int[] as an Open Type are necessarily new and existing model-specific clients cannot know those new models.

Recommended Fix
Handle arrays of primitive wrapper types defined in Open MBeans using the class java.lang.reflect.Array to avoid possible ClassCastExceptions.

Further Reading


CompositeDataSupport.equals now compares arrays element-by-element

Description
If you call cd1.equals(cd2), where cd1 is a CompositeDataSupport and cd2 is an object implementing CompositeData (i.e., another CompositeDataSupport), and if cd1 and cd2 have the same CompositeType that includes at least one item of type ArrayType, then the contents of each such array should be compared element by element. Currently only the array identities are compared, which means that equals returns true if the two objects refer to the same array but not if they refer to different arrays with the same contents.

Consequence Without Action
The following interoperability issue may arise when a client running J2SE 1.5 is connected using the JMX Remote API to a server running Java SE 6, or vice versa.

In the case that two CompositeDataSupport objects both have ArrayType values, and the two values are different objects but equal, it will return false if calling the method equals from J2SE 1.5 or earlier, but get true from JDK 6.

Recommended Fix
Code that depended on the previous incorrect behavior will need to be changed.

Further Reading


2.1.9 Networking

 

HttpURLConnection sets Content-Type to application/x-www-form-urlencoded

Description
Formerly, the HTTP protocol handler set a default Content-Type field. This caused problems for applications that were not expecting a Content-Type to be set. However, applications that depend on the default setting of Content-Type, will have to explicitly set it now.

Further Reading


2.2 Source Incompatibilities

 

This section contains a listing of issues for the Java Developer where an application that was compiled under J2SE 1.5 may continue to run unchanged on Java SE 6, but its source code may not compile using the Java SE compiler. An example of this kind of issue is of a platform API Interface that has added a new method for Java SE 6.

2.2.1 JMX

 

Two changes can potentially lead to source code that compiled on J2SE 1.5 no longer compiling on Java SE 6.

Generification of the two-argument constructor to StandardMBean in JMX API

Description
While generifying the JMX API the two-argument constructor to StandardMBean has acquired a type constraint:

<T> StandardMBean(T impl, Class<T> intf)

Consequence Without Action
Generification of the two-argument constructor to StandardMBean means that if the second parameter is a class literal such as SomethingMBean.class, then the first parameter must be an object that has been declared as being of that type or a subtype.

For example, the following code will no longer compile:

Object impl = new SomethingImpl(); Object mbean = new StandardMBean(impl, SomethingMBean.class); mbeanServer.registerMBean(mbean, objectName);

The compiler will reject the new StandardMBean line with a message like this:

Test.java:10: cannot find symbol symbol: constructor StandardMBean( java.lang.Object, java.lang.Class<com.example.SomethingMBean>) location: class javax.management.StandardMBean

Recommended Fix
The fix is either to change the declaration of impl from Object to SomethingImpl or SomethingMBean or to add a cast in the call to the constructor:

Object mbean = new StandardMBean((SomethingMBean) impl, SomethingMBean.class);

Further Reading


New Descriptor support in Open MBeans can lead to ambiguity errors

Description
In J2SE 1.5, Model MBeans support Descriptors to supply additional metadata about the MBean. A Descriptor is essentially a Map that contains metadata items. A Descriptor can be attached to the ModelMBeanInfo to describe the MBean itself, and to the various ModelMBean*Info classes (ModelMBeanAttributeInfo, etc.) to describe the components of the MBean. In Java SE 6, the use of Descriptors has been extended to all type of MBeans.

The addition of a new constructor to OpenMBeanParameterInfoSupport that adds an extra Descriptor parameter can potentially create ambiguity.

Consequence Without Action
The addition of the new constructor to OpenMBeanParameterInfoSupport means that an invocation like this:

new OpenMBeanParameterInfoSupport(name, description, openType, null);

becomes ambiguous, since null matches both the constructor where the fourth parameter is a Descriptor and the constructor where it is a defaultValue.

Recommended Fix
You can resolve the ambiguity by adding a cast as follows:

new OpenMBeanParameterInfoSupport (name, description, openType, (Descriptor) null); new OpenMBeanParameterInfoSupport (name, description, openType, (Object) null);

In the second case, you can also call the three-argument constructor which is equivalent when the defaultValue is null.

Further Reading


2.2.2 JVM TI

 

Added Category:

"Heap" : heap functionality which supports reporting primitive values, allows setting the referrer tag, and has more powerful filtering. Added:

Added Other Functions:


Added Events:


New JVM TI capabilities of the Java SE HotSpot virtual machine


2.2.3 Java compiler

 

Description
By default, the compiler will generate class files using the new class file format (see http://jcp.org/en/jsr/detail?id=202). In rare cases, some programs will fail to compile because limitations in the class file format are exceeded.

Further Reading


2.3.Dependencies on Implementation Mechanisms

 

This section deals with issues for the Java developer where an application depends on an implementation-specific behavior of the Java SE platform APIs. An example of such a feature is the particular format of the toString() method of a class. While the platform specification does not define what that format should be, a Java developer may have created an application that depends on being able to parse the format of the toString() method as in Sun's implementation.

2.3.1 Runtime Dependencies

 

A number of bugs fixed in JDK 6 classfile conformance checking dealing with specification conformance.

Most fixes are tied to the classfile version to maintain compatibility with older, possibly nonconformant classfiles. Occasionally we have flags to revert to old behavior (as noted):

6253381: -Xcheck:jni JNI call made with exception pending should be a warning

6444959/6374692: NullPointerException without user code in stack trace when running under N1 Grid Engine 6.0u8

(this is a bug that requires a patch and has a workaround -it will also be in the release notes )

2.3.2 AWT

 

Changes in keyboard handling

Description
With this fix, in XAWT only, the user can easily switch between multiple keyboard layouts without changing a locale. There is presently a direct mapping between X keysyms and Unicode, when possible. As a by-product, this eliminates several deadkey issues, problems with national keyboards, etc.

Consequence Without Action
Possible pitfalls here may be with Input Methods. Java keyboard machinery seems working well with standard XIM.

Recommended Fix
No updates to existing code are required.

Further Reading


2.3.3 Java 2D

 

Changes in stroking and filling some shapes 

Description
JDK 6 has changes to the implementation of some stroke and fill operations which were designed to improve the overall quality of curved shapes and to have more consistency between a stroked shape and the same shape when filled. In some cases, pixels that used to be touched will no longer be touched. In other cases, pixels that were not previously touched will now be touched.

Consequence Without Action
Since the latter change in behavior can extend the area of a fill, it may cause a noticeable difference with very small shapes such as bullets or tick marks when they are tightly enclosed in a component if the fill extends an additional pixel and overlaps the border of the component.

Recommended Fix
This may be worked around in some cases by

graphics2d.setRenderingHint( RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);

which may produce results closer to the old behavior. Alternatively the shape can be adjusted to fit.

2.3.4 Beans

 

Enum classes are supported with XMLEncoder.

Description
XMLEncoder does not serialize enumeration correctly and the result data is lost. Now XMLEncoder serializes enumeration correctly.

Consequence Without Action
Internal EnumPersistenceDelegate will be used instead of the user's custom persistence delegate for Enum subclasses.

Recommended Fix
It is not necessary to use the user's persistence delegates. These classes can be removed.

Further Reading


A number of bugs fixed in Long Term Persistence mechanism.

Description
XML serialization format did not change, but a number of bugs were fixed to improve it:

Consequence Without Action
None. Long Term Persistence works more smoothly.

Recommended Fix
No updates to existing code are required.

Further Reading


2.3.5 JVM TI

 

Attach mechanism added to the Java SE HotSpot virtual machine, allowing JVM TI agents to be attached to a running application.

Description
Removes the requirement that an agent be started at VM start time

Consequence Without Action
None

Recommended Fix
Agents should be modified to support this new feature


2.4.Deprecated APIs

 

This section contains a list of all the deprecated APIs and their replacements for Java SE 6.

2.4.1 JMX

 

In the Java class javax.management.openmbean.OpenType, the mutable ALLOWED_CLASSNAMES string array has been deprecated and a new unmodifiable string list ALLOWED_CLASSNAMES_LIST should be used instead.

@Deprecated

public static final String[] ALLOWED_CLASSNAMES

instead use

public static final List<String> ALLOWED_CLASSNAMES_LIST

2.4.2 JVM TI

 

A new set of functions has been added to JVM TI to expand the capabilities of the heap analysis functionality. This new heap functionality supercedes the old "Heap (1.0)" functionality.The old heap functions and tendrils are deprecated. Going forward, agents should transition to using the new functionality.

Deprecated Functions:

Deprecated Function types:

Deprecated Types:

2.5 Reserved Keywords

 

This section lists new keywords or symbols for Java SE 6.

2.5.1 JMX

 

The string // (two slashes) is now reserved in the domain part of an ObjectName. Code that uses it will continue to work because it does not yet have any special interpretation, but such code should be changed before the next release of the Java platform, Java SE 7, where the string will acquire an interpretation in connection with MBean naming hierarchies.

2.6 New Features or APIs of Note During Migration

 

This section contains a listing of new features or APIs that a Java developer may choose to take advantage of in upgrading to JDK 6 in order to improve existing application code. This is not an complete listing of all the new functionality in Java SE 6 , rather this should be considered as a tip sheet for new features that specifically provide a much improved or reliable way of performing a task than existed in J2SE 1.5.

2.6.1 Runtime

 

For JNI developers: new jni_ObjectReferenceType returns local/global/weak/unknown jobject type

Description
Developer requested ability to determine type of a jobject. This can help with ensuring that appropriate Deletes are called so that memory is freed.

Further Reading


Improved diagnostics

Description
Added DTrace probes to the VM to improve diagnostics

Now on Solaris 10 and later, DTrace is being ported to other platforms

Further Reading


LinkageError: loader constraints.

Description
The error message has been improved to give more information, such as the types of the two conflicting classloaders. In addition, -XX:+TraceLoaderConstraints, a new diagnostic java command line flag which traces additions, modifications, and removal of loader constraints has been added.

Further Reading


2.6.2 Monitoring and Management

 

java.lang.management API supports monitoring of java.util.concurrent locks

Description
J2SE 1.5 provided an API to obtain the monitor lock information when a thread is blocked or waiting on a monitor. ThreadMXBean.findMonitorDeadlockedThreads() provides a programmatic way to detect deadlock on demand. Both provide lock information about the object monitor lock but not java.util.concurrent locks.

Consequence Without Action
None. In JDK 6, java.lang.management.ThreadInfo reports the monitor lock or java.util.concurrent ownable synchronizer that a thread is blocked or waiting on without any code modification.

Recommended Fix
Use the new API to obtain information about java.util.concurrent ownable synchronizers.

Further Reading


java.lang.management API to obtain the list of locks owned by a thread

Description
New programmatic way to obtain the list of locks owned by a thread for diagnosing thread problems.

Consequence Without Action
No owned locks are included in ThreadInfo objects

Recommended Fix
Use the new dumpAllThreads or getThreadInfo methods in order to obtain owned locks information.

Further Reading


API to get system load average

Description
New ability to get system load average

Recommended Fix
Use the new method to get system load average. On Windows, the load average is not available and the method will return -1.

Further Reading


New com.sun.management.HotSpotDiagnosticMXBean class

Description
New API to enhance the diagnosability of the HotSpot VM. For example, to get a heap dump and set and get VM option.

Recommended Fix
Use the new API or jconsole to access the HotSpot enhanced diagnosability.

Further Reading


Dynamic attach mechanism (new com.sun.tools.attach API)

Description
New API for a tool to attach to a JVM, load an agent, and get system properties

Recommended Fix
Use the new API to develop a tool that dynamically attaches to a running VM.

Further Reading


New JConsole plugin API (com.sun.tools.jconsole API)

Description
Provide a jconsole plug in interface for the user to define custom tabs.

Further Reading


2.6.3 JDI and JDWP

 

JDI
Below is a list of new methods and interfaces added to JDI in JDK 6. Equivalent commands or events have been added to JDWP. For more information, see: http://java.sun.com/javase/6/docs/technotes/guides/jpda/enhancements.html List<ObjectReference> ObjectReference.referringObjects(long maxReferrers); List<ObjectReference> ReferenceType.instances(long maxInstances); int ReferenceType.majorVersion(); int ReferenceType.minorVersion(); int ReferenceType.constantPoolCount(); byte[] ReferenceType.constantPool(); ListK<Value> StackFrame.getArgumentValues(); List<MonitorInfo> ThreadReference.ownedMonitorsAndFrames() void ThreadReference.forceEarlyReturn(Value value) VoidValue VirtualMachine.mirrorOfVoid(); boolean VirtualMachine.canGetMethodReturnValues(); boolean VirtualMachine.canGetInstanceInfo(); boolean VirtualMachine.canUseSourceNameFilteres(); boolean VirtualMachine.canForceEarlyReturn(); boolean VirtualMachine.canRequestMonitorEvents(); boolean VirtualMachine.canGetMonitorFrameInfo(); boolean VirtualMachine.canGetClassFileVersion(); boolean VirtualMachine.canGetConstantPool(); boolean VirtualMachine.canGetClassFileVersion(); long[] VirtualMachine.instanceCounts(List<extends ReferenceType> refTypes); Value MethodExitEvent.returnValue(); void ClassPrepareRequest.addSourceNameFilter(String sourceNamePattern); MonitorContendedEnterRequest EventRequestManager.createMonitorContendedEnterRequest(); MonitorContendedEnteredRequest EventRequestManager.createMonitorContendedEnteredRequest(); MonitorWaitRequest EventRequestManager.createMonitorWaitRequest(); MonitorWaitedRequest EventRequestManager.createMonitorWaitedRequest(); List<MonitorContendedEnterRequest> EventRequestManager.monitorContendedEnterRequests(); List<MonitorContendedEnteredRequest> EventRequestManager.monitorContendedEnteredRequests(); List<MonitorWaitRequest> EventRequestManager.monitorWaitRequests(); List<MonitorWaitedRequest> EventRequestManager.monitorWaitedRequests();

New com.sun.jdi.events events:

MonitorContendedEnterEvent MonitorContendedEnteredEvent MonitorWaitEvent MonitorWaitedEvent

New com.sun.jdi.request requests:

MonitorContendedEnterRequest MonitorContendedEnteredRequest MonitorWaitRequest MonitorWaitedRequest

New connector for connecting to a process-id:

com.sun.jdi.ProcessAttach  

2.6.4 Swing

 

Ability to reset a ButtonGroup to an unselected state

Description
The ButtonGroup class is used to create a mutual-exclusion scope for a set of buttons. Initially all buttons in a ButtonGroup are unselected. Previously, once a button in a group was selected there was no programmatic way to clear the selection in the group; one button always had to remain selected. A new method, clearSelection(), has been added to ButtonGroup.

Further Reading


New constants for javax.swing.Action interface

Description
Swing's Action interface lacked some of the abilities provided by button. Most notable is the ability for the Action to have a selected state. In addition to fixing multiple inconsistancies in how various components support Actions the following new constants have been added to Action:

In addition, the new method setHideActionText has been added to AbstractButton. This method allows you to control whether or not the text of the button should come from the Action. This is useful when a button is used in a toolbar and a menu and you do not want the toolbar button to show text.

Further Reading


Use of arbitrary JComponents as JTabbedPane tab labels

Description
Many applications such as Mozilla, support a richer user experience with components (such as close buttons) embedded in tabs. This ability was not previously available in Swing, as tabs in JTabbedPane could only contain an icon, text and/or html. Three new methods have been added to JTabbedPane to allow adding components as labels to tabs in a JTabbedPane, setTabComponentAt getTabComponentAt, and indexOfTabComponent.

Further Reading


Enhanced drop experience for Swing DnD

Description
Previously, Swing had very limited support for accepting drops of data into components. There were two major problems:

  1. A drop location was indicated by moving the selection around within the component under which DnD was occurring. This fired unnecessary selection events, was not customizable, and was hardly ever what was wanted. For example, it did not allow dropping between items in lists, tables, and trees.
  2. Swing provided no support for customizing what data could be inserted at what locations in the component. The developer was provided very little detail about the actual transfer when asked whether or not they would accept it, were only asked once (not based on position in the component), were given the same little information when it was time to import the data.

The purpose of this change was to provide a very usable and customizable data transfer/DnD API in Swing.

The following have been changed/added:

  1. An API was added allowing developers to specify one of a handful of new drop modes on components supporting drops. JList, JTable, JTree and JTextComponent now have a setDropMode() method that takes a new DropMode type. This provides more flexibility on how data can be inserted . The drop locations are now indicated without affecting selection. Drop locations are calculated based on the drop mode, and are returned to the developer during DnD.
  2. Overloaded versions of two methods, canImport() and importData() have been provided in TransferHandler that take a TransferInfo object containing the needed details of a transfer. By default, these new methods call the old versions. In addition, a new method, shouldIndicate() has been added to TransferHandler to allow for further customization of when to show the drop location.
  3. The internal implementation of Swing DnD was re-designed to reduce the number of classes and get rid of the exceptions.

Further Reading

Additionally there were minor problems, such as exceptions being thrown, in the implementation. The following bugs were also addressed by this feature (many of these with multiple duplicates):


Allow setting a TransferHandler on a top level window

Description
Some native applications allow data to be imported by dragging the data and dropping it anywhere within a frame, i.e., a text editor can allow files to be dropped anywhere on top of it (including its title bar) to initiate opening that file. This was previously possible in Swing only by creating your own drop support. The Swing TransferHandler, which was designed to simplify DnD in Swing, did not support this. setTransferHandler and getTransferHandler methods were added to JFrame, JDialog, JWindow and JApplet to support DnD on top level windows.
Further Reading


Inclusion of SwingWorker with Java SE

Description
To effectively create some Swing applications one needs to use multiple threads. Swing is not thread safe, which makes this a daunting and arduous task. SwingWorker, which was originally published on Sun's website more than 6 years ago, eases multi-threaded programming with Swing. This is something that becomes more useful as developers must interact with remote services. Since it was published, countless developers have requested we add it into core. A new and improved version of SwingWorker has been added to the javax.swing package.

Further Reading


Printing support for text components

Description
Previously, Swing's text components provided no direct support for printing, leaving a challenge to developers. Three new print() methods and one new getPrintable() method were added to JTextComponent to offer printing support.

Further Reading


Ability to get the baseline for components

Description
Professional layouts typically align components along their baseline. Previously, Swing did not provide a way to get the baseline of components. To solve this, the methods getBaseline() and getBaselineResizeBehavior() have been added to java.awt.Component. JComponent overrides these and forwards to the appropriate UI classes. The UI classes override these methods to return the baseline. GridBagLayout and FlowLayout have been given new API to align the components along their baseline.

Further Reading


Ability to get the preferred padding between components

Description
Each look and feel provides guidelines as to how far apart components should be placed. In order to create a cross platform look and feel, there should be an API for determining this. A new class, javax.swing.LayoutStyle, has been added. LayoutManagers can use this class to determine the ideal amount of space to place between components. Look and feel authors can provide a custom LayoutStyle by way of overriding the LookAndFeel method getLayoutStyle().

Further Reading


Addition of a GroupLayout LayoutManager

Description
A new layout manager, GroupLayout, has been added to the javax.swing package. This LayoutManager, aimed at making a better tools experience, can be seen in NetBeans' Matisse.

Further Reading


Sorting and Filtering support for JTable

Description
Most client applications usingJTable require sorting and filtering. Sorting and filtering APIs were added to JTable. Sorting can now be enabled by specifying a RowSorter on JTable. For example, the following line enables sorting:

table.setRowSorter(new TableRowSorter(model));

Filtering can be added using a RowFilter. Implementations exist for filtering on numbers, dates and strings.

Further Reading


2.6.5 AWT

 

Enhancements for modality support

Description
With the fix for CR 4080029 (integrated to JDK6 b38), many problems were fixed and improvements were implemented in the AWT modality area. As part of this feature, constructors of top levels were changed to accept null as an owner, thus Frame is not the only top level which can be created without an owner now.

Further Reading


Splash screen for Java startup

Description
It is possible to show splash screen on Java startup with either command line option -splash or by specifying a splash image in a jar file which is executed with -jar option.

Further Reading


New API to get location of MouseEvent in screen coordinates

Description
Previously, additional translation was necessary to obtain screen coordinates of the mouse events. This translation could lead to hard to diagnose problems if the window moved after the firing event. New methods MouseEvent.getLocationOnScreen() , MouseEvent.getXOnScreen(), and MouseEvent.getYOnScreen() can now be used to obtain absolute coordinates on the screen from MouseEvent.

Further Reading


MouseAdapter now implements MouseMotionListener and MouseWheelListener

Further Reading


New API to detect if always-on-top is supported by platform

Further Reading


Improved icon support

Description
Previously, the API was allowed to set only one icon image for the Frame, and scaled it to all required sizes. Meanwhile, native windowing systems (such as Windows, Gnome and KDE) use several images of different size to represent the same top level (e.g., an icon for the title of the top level, an icon for an item in task bar, an icon for an item in the Alt-Tab list). Another limitation of the old API was that a developer could specify icon for Frames but not for Dialogs, so all owned dialogs inherited icons from parents and all ownerless dialogs had a default Java icon. A new method, setIconImages(List), has been added to Window to allow setting multiple icons for both Frames and Dialogs.

Further Reading


API to launch desktop helper applications

Description
Every modern desktop provides some common services, such as a browser, mailer and editor. New class java.awt.Desktop has been added to provide access to these services.

Further Reading


2.6.6 I18N

 

java.util.ResourceBundle improvements

Description
java.util.ResourceBundle has been improved so that applications can control the java.util.ResourceBundle.getBundle behavior. Refer to java.util.ResourceBundle.getBundle and java.util.ResourceBundle.Control documentation.

Further Reading


Rounding modes in java.text.NumberFormat

Description
java.text.NumberFormat now supports rounding modes. Refer to the java.text.NumberFormat.setRoundingMode documentation.

Further Reading


New constructor in java.util.PropertyResourceBundle

Description
The new java.util.PropertyResourceBundle constructor takes a java.io.Reader so that properties files in any encoding can be read. Refer to the java.util.PropertyResourceBundle(java.io.Reader) documentation.

Further Reading


Extendable java.text.CollationKey

Description
java.text.CollationKey is now non-final so that it can be extended.

Further Reading


2.6.7 Beans

 

Annotation to link constructor parameters to getters

Description
An annotation @ConstructorProperties was introduced. It can be attached to a constructor to establish the relationship between the constructor parameters and the class properties. This is exactly what the constructor DefaultPersistenceDelegate(String[] constructorPropertyNames) does. Defining the annotation removes the need to code a DefaultPersistenceDelegate explicitly, and it is useful outside the java.beans framework.

Consequence Without Action
None

Recommended Fix
If DefaultPersistenceDelegate is registered with XMLEncoder for your class each time, you can replace all such usages with the annotation @ConstructorProperties before the appropriate constructor.

Further Reading


2.6.8 JMX

 

Newly introduced type of MBean:MXBeans

An MXBean is defined by writing a Java interface called SomethingMXBean and a Java class that implements that interface. Every method in the interface defines either an attribute or an operation in the MXBean. The annotation @MXBean can be also used to annotate the Java interface instead of requiring the interface name be followed by the MXBean suffix.

MXBeans provide a convenient way to bundle related values together in an MBean without requiring clients to be specially configured to handle the bundles when interacting with that MBean.

This is an incremental change, because MXBeans already existed in J2SE 1.5, in the package java.lang.management. What is new is that users can now define their own MXBeans, in addition to the standard set defined in java.lang.management.

The key idea behind MXBeans is that types such as java.lang.management.MemoryUsage that are referenced in the MXBean interface, java.lang.management.MemoryMXBean in this case, get mapped into a standard set of types, the Open Types that are defined in the package javax.management.openmbean. The exact mapping rules appear in the MXBean specification, but to oversimplify we could say that simple types like int or String are unchanged, while complex types like MemoryUsage get mapped to the standard type CompositeDataSupport.

Descriptors and DescriptorKey

Descriptors give you a convenient way to attach arbitrary extra metadata to your MBeans. This is an incremental change because Descriptors have always existed in the JMX API, but only in conjunction with Model MBeans. In Java SE 6, Descriptors are available with all types of MBeans.

For most constructors in the classes MBean*Info (MBeanInfo, MBeanAttributeInfo, etc.), a parallel constructor has been added with the same parameters plus an additional Descriptor parameter. Likewise for OpenMBean *InfoSupport. The MBean*Info and OpenMBean *InfoSupport classes now contain a getDescriptor() method.

Open MBeans return information about default and legal values from the getDefaultValue(), getLegalValues(), getMaxValue(), and getMinValue() methods of OpenMBeanParameterInfo and OpenMBeanAttributeInfo. This information is now also present in the corresponding Descriptors, and other types of MBean can also return the information in their Descriptors.

A new annotation DescriptorKey can be used to add information to the Descriptors for a Standard MBean (or MXBean) via annotations in the Standard MBean (or MXBean) interface. This makes it possible for a tool that generates Standard MBeans from an existing management model to include information from the model in the generated MBean interfaces, rather than in separate files.

For example, with this definition:

@Documented @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface Units { @DescriptorKey("units") String value(); }

you can define an annotation @Units that you can then use as follows:

public interface CacheMBean { @Units("whatsits") public int getUsed(); }


New static methods to create proxies for Standard MBeans and MXBeans

Four new static methods to create proxies for Standard MBeans and MXBeans have been defined in the javax.management.JMX class.

newMBeanProxy(connection, name, interfaceClass);
newMBeanProxy(connection, name, interfaceClass, notificationBroadcaster);
newMXBeanProxy(connection, name, interfaceClass);
newMXBeanProxy(connection, name, interfaceClass, notificationBroadcaster);

MBean proxies allow you to access an MBean through a Java interface, allowing you to make calls on the proxy rather than having to write lengthy code to access a remote MBean.

For example:

SimpleStandardMBean proxy = JMX.newMBeanProxy( mbsc, stdMBeanName, SimpleStandardMBean.class, true);

An MBean proxy for SimpleStandardMBean is created here by calling the method newMBeanProxy() in the javax.management.JMX class, passing it the MBean's MBeanServerConnection, object name, the class name of the MBean interface and true, to signify that the proxy must behave as a NotificationBroadcaster.

You can make proxies for MXBeans in exactly the same way as for Standard MBeans, by simply calling newMXBeanProxy(), instead of newMBeanProxy().

Add ObjectName constants to JMX API

public static final ObjectName javax.management.MBeanServerDelegate.DELEGATE_NAME

Defines the default ObjectName of the MBeanServerDelegate.

public static final ObjectName javax.management.ObjectName.WILDCARD

Defines the wildcard "*:*" ObjectName.

Support key=* wildcard in ObjectName

ObjectName wildcards in keys:

In J2SE 1.5 you could say domain:key1=value1,* to match MBeans that have key1=value1 in their name, but not domain:key1=* to match MBeans that have key1 in their name.

The ObjectName functionality has been extended in Java SE 6 such that you can put a wildcard (* and/or ?) anywhere in a value, e.g., key=a*b as well as key=*. The asterisk matches any sequence of zero or more characters, while the question mark matches any single character.

2.6.9 Java 2D

 

Image I/O GIF writer

Description
The javax.imageio package has added a GIF image writer as a standard plug-in. Applications can now write images as GIFs in the same way as other image formats, for example:

javax.imageio.ImageIO.write(img, "gif", new File("out.gif"));

Applications which are written to present to a user all available image writers will not need to be updated to take advantage of this new plug-in.


Multi-stop gradient paint

Description
Two new gradient paint implementations have been added that can be used to easily create visually appealing graphical effects in applications.

For example, to create a simple radial gradient where the colours emanate from the center point interpolating in a distribution where the center is red, at the 0.2 fractional distance, it is white, and the perimeter of the circle is blue, one would code:

Point2D center = new Point2D.Float(50, 50); float radius = 25; float[] dist = {0.0f, 0.2f, 1.0f}; Color[] colors = {Color.RED, Color.WHITE, Color.BLUE}; RadialGradientPaint p = new RadialGradientPaint(center, radius, dist, colors);


Further Reading
See the documentation for these classes for more information including additional sample code and images.


Path2D : double and single precision paths

Description
The java.awt.geom.GeneralPath class in previous releases provided only for float precision storage of coordinates. This was too limiting for some applications. Java SE 6 adds a new superclass, java.awt.geom.Path2D, which has double precision (java.awt.geom.Path2D.Double) and single precision (java.awt.geom.Path2D.Float) subclasses. java.awt.geom.GeneralPath is now an empty subclass of Path2D.Float.

Applications which want to use double precision coordinates must use the new Path2D.Double class. Applications which do not need this precision can continue to use GeneralPath or can use the new Path2D.Float class.

Further Reading
See the specification of these classes for more information.


Font Smoothing and LCD Sub-Pixel text.

Description
Using Java2D APIs it is now possible to use desktop font/text settings in Swing components. The Java 2D APIs which enable this are new rendering hints values for the text antialiasing hint java.awt.RenderingHints.KEY_TEXT_ANTIALIASING. The most important of these new values are java.awt.RenderingHints.VALUE_TEXT_ANTIALIAS_GASP (the equivalent to the Windows "Standard Font Smoothing" Setting) and java.awt.RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB (the equivalent to the Windows "ClearType" Setting).

The supported mechanism for querying and using the settings that correspond to the Windows desktop setting is to query the AWT desktop property awt.font.desktophints and set it on the Graphics instance of your component as follows :

Toolkit tk = Toolkit.getDefaultToolkit(); Map map = (Map)(tk.getDesktopProperty("awt.font.desktophints")); RenderingHints oldHints = null; if (map != null) { oldHints = graphics2D.getRenderingHints(); graphics2D.addRenderingHints(map); } /* Draw your text label etc */ ... /* finally restore the original hints */ if (map != null) { graphics2D.setRenderingHints(oldHints); }

Note that this should not be used for built-in Swing components, which manage this automatically. Use it only for your custom components.

Required action
For the standard JDK Swing L&Fs such as Metal (also known as Java L&F), Windows, GTK, there is no action needed on the part of the application. However Custom L&Fs and custom components which want to use these new capabilities will need to be updated.

Further Reading
See the documentation for java.awt.Toolkit.getDesktopProperty(String) for a link to a full specification.


Registering Fonts java.awt.Font's created from a file or stream.

Description
Fonts created with java.awt.Font.createFont() previously were not available to Font constructors. In Java SE 6 a new method has been added, java.awt.GraphicsEnvironment.registerFont(java.awt.Font), that allows these fonts to be made available to new Font constructors. For example:

Font font = Font.createFont(Font.TRUETYPE_FONT, new File("myfont.ttf")); graphicsEnvironment.registerFont(font); Font newFont = new Font(font.getFontName(), Font.PLAIN, 12);


Using Fonts with Text Attributes

Description
Java 2D text rendering now supports additional text attributes, notably kerning, and optional ligatures. In addition, all text attributes can be applied as Font attributes which greatly eases using these in applications. For example, to specify that text be drawn in a font applying optional ligatures and kerning information an application may code:

Font font = new Font("Times New Roman", Font.PLAIN, 12); map.put(TextAttribute.LIGATURES, TextAttribute.LIGATURES_ON); map.put(TextAttribute.KERNING, TextAttribute.KERNING_ON); font = font.deriveFont(map); graphics2D.setFont(font); graphics2D.drawString("Some text", 100, 100);


Further Reading
See the documentation of java.awt.font.TextAttribute for more information.


Path2D: New hit testing facil