![]() |
JDKTM6 Adoption Guide
Revision 1.0.8 |
JDK Documentation Contents |
1.1 Purpose of this Document
1.2 How this Document is Structured2 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 Migration3 Deployment and Configuration Issues
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.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 Other4 Tools and Platform Developer Issues
3.6.1 Networking
3.6.2 Deployment
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
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.
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:DetachCurrentThreadshould release thread-owned monitors. The JNIDetachCurrentThreadspecification 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 JNIDetachCurrentThreadoperation 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:-JNIDetachReleasesMonitorsto 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:-JNIDetachReleasesMonitorsmay be specified on the command line to revert to the pre-JDK 6 behavior.Further Reading
- CR 6336479
- http://java.sun.com/javase/6/docs/technotes/guides/jni/spec/invocation.html#detach_current_thread
2.1.2 JVM TI
GetVersionNumber returns 1.1.
Description
This is a new version of JVM TIConsequence Without Action
None, unless the caller does not allow for this valueRecommended Fix
None, unless the caller does not allow for this valueFurther Reading
- JVM TI spec
- CR 6263703
Specify that static field indices are defined the same as instance field indices.
Description
This was needed for some of the heap walking functionalityConsequence Without Action
NoneRecommended Fix
NoneFurther Reading
- JVM TI spec
In GetThreadListStackTraces, add JVMTI_ERROR_INVALID_THREAD error to cover an invalid thread in the list.
Description
None of the universal errors cover this caseConsequence Without Action
NoneRecommended Fix
Could check for this error and give a more meaningful error messageFurther Reading
- JVM TI spec
- CR 6392604
Disallow NULL for the heap_object_callback parameter of IterateOverHeap and IterateOverInstancesOfClass functions.
Description
Made spec match behaviorConsequence Without Action
NoneRecommended Fix
NoneFurther Reading
- JVM TI spec
Change IsMethodObsolete to no longer require the can_redefine_classes capability.
Description
An additional way of modifying classes was introduced, seeRetransformClassesbelow, which has its own capabilities. Rather than adding more capabilities needed forIsMethodObsolete, it made more sense to just remove the need for any capability.IsMethodObsoleteis meaningful even if no redefine or retransform capabilities exist ; it will just always return false.Consequence Without Action
NoneRecommended Fix
NoneFurther Reading
- JVM TI spec section on 'Obsolete Methods'
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
NoneRecommended Fix
NoneFurther Reading
- JVM TI spec
- CR 6346327
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 clearConsequence Without Action
NoneRecommended Fix
NoneFurther Reading
- JVM TI spec
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
NoneRecommended Fix
NoneFurther Reading
- JVM TI spec
Clarify that exception events cover all Throwables.
Description
It was not clear that all Throwables are reported.Consequence Without Action
NoneRecommended Fix
NoneFurther Reading
- JVM TI spec
- CR 6330025
In GetThreadListStackTraces, specify that unstarted threads return empty stacks.
Description
An oversight in the specConsequence Without Action
NoneRecommended Fix
NoneFurther Reading
- JVM TI spec
- CR 6392604
Clarify that exactly one Agent_OnLoad (or Agent_OnAttach) is called per agent.
Description
It was not clear that this happened, for example iffoois loaded via the command line and later viaattachConsequence Without Action
NoneRecommended Fix
NoneFurther Reading
- JVM TI spec
- CR 6434824
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
NoneRecommended Fix
If an agent was set up to allow for exceptions, it could be simplified.Further Reading
- JVM TI spec
- CR 6426916
Clarify the heap_object_callback parameter of IterateOverHeap and IterateOverInstancesOfClass functions.
Description
The spec contained an incorrect definition of this parameter.Consequence Without Action
NoneRecommended Fix
NoneFurther Reading
- JVM TI spec
Clarify that IterateOverInstancesOfClass includes subclasses.
Description
The spec did not state thisConsequence Without Action
NoneRecommended Fix
Be sure agents are coded to expect this.Further Reading
- JVM TI spec
- CR 6391924
Clarify the timing of the MonitorWait and MonitorWaited events.
Description
The spec was not clear on when these events would be generatedConsequence Without Action
NoneRecommended Fix
None, just be aware of the new wordingFurther Reading
- JVM TI spec
- CR 6455248
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
NoneRecommended Fix
NoneFurther Reading
- JVM TI spec
- CR 6252173
Clarify that memory allocated by JVM TI must be freed by JVM TI and vice versa.
Description
Mixing allocates/frees will not workConsequence Without Action
NoneRecommended Fix
NoneFurther Reading
- JVM TI spec
- CR 6196685
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 forJComponent.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 whereJTabbedPanedid not firestateChangeevents, 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.JTabbedPaneselection 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)orJDialog(Dialog). Also, acreateDialog(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
NoneRecommended Fix
No updates to existing code are required.Further Reading
Using Ctrl-Shift-Clicking to create disjoint selection intervals
Description
JTable,JList, andJTreedid 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 theJTable.changeSelection()method.JTable.changeSelection()takes a set of boolean parameters (toggleandextend) 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
NoneRecommended Fix
No updates to existing code are requiredFurther Reading
Better documentation for JDialog.setDefaultCloseOperation()
Description
javax.swing.JDialog.setDefaultCloseOperation()was identified as having poor documentation in compared to its counterpart injavax.swing.JFrame.setDefaultCloseOperation(). The documentation needed to be fixed. In addition, theJDialogversion didn't fire a property change and throw anIllegalArgumentExceptionlike itsJFramecounterpart. The documentation was updated to be much clearer. A property change event is now fired, like forJFrame, and the method will now throw anIllegalArgumentExceptionfor bad arguments, includingJFrame.EXIT_ON_CLOSEwhich previously resulted in no action..Consequence Without Action
IllegalArgumentExceptioncan be thrown if your code passes an invalid value tosetDefaultCloseOperation.Recommended Fix
Ensure any calls tosetDefaultCloseOperationonJDialoguse one of the valid values. This does not includeJFrame.EXIT_ON_CLOSE.Further Reading
Specifying constraints on SpringLayout was order dependent
Description
SpringLayoutallows developers to specify threeSpringsalong each axis that dictate the size and position of a component. Only twoSpringsare 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.SpringLayoutnow 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 onSpringLayoutto constrain ordering, it might cause an incorrect layout in JDK 6.Recommended Fix
Update existing code to remove dependencies onSpringLayoutconstraint orderingFurther Reading
2.1.4 AWT
Minimum size for java.awt.Frame is now being enforced.
Description
The methodWindow.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
- API documentation for
Window.setMinimumSize()- CR 4320050
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 SolarisRecommended Fix
If you need to useMToolkityou need to set theAWT_TOOLKITenvironment variable toMToolkitFurther Reading
- API documentation for
Toolkit.getDefaultToolkit()- CR 5049146
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 thejava.util.TimeZone.useDaylightTime()value into account when the daylight saving time name is requested so thatjava.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 ifjava.util.TimeZone.useDaylightTime()returns 'false'.Recommended Fix
None
Further Reading
java.text.Collator.getInstance() change
Description
java.text.Collator.getInstance()does not always return ajava.text.RuleBasedCollatorinstance. Thejava.text.RuleBasedCollatordocumentation has been updated.Consequence Without Action
If an application assumes the returned instance is aRuleBasedCollatorinstance, aClassCastExceptionorNoSuchMethodExceptionmay be thrown, depending on how the application deals with the returned instance.Recommended Fix
If the application tries to issue aRuleBasedCollatorinstance specific method, do so after checking it with 'instanceof' condition.Further Reading
java.text.BreakIterator changes
Description
java.text.BreakIterator.preceding(int)andjava.text.BreakIterator.isBoundary(int)accept the last boundary of the text which is returned fromjava.text.BreakIterator.last(). Previously, these methods threw anIllegalArgumentExceptionwith the last text boundary.Consequence Without Action
IllegalArgumentExceptionwill not be thrown inpreceding()orisBoundary()methods with the last boundary as a parameter.Recommended Fix
NoneFurther Reading
Locale sensitive services no longer fall back to the default locale
Description
The locale sensitive classes in thejava.textandjava.utilpackages, such asjava.text.DateFormat, no longer fall back to thedefault java.util.Localewhen any locale sensitive service for the givenjava.util.Localeis not found. The fallback to the defaultjava.util.Localeis often seen as a confusion rather than as a convenience.Consequence Without Action
Fallback to the default locale will not take placeRecommended Fix
NoneFurther Reading
2.1.6 Javasound
Synthesizer.remapInstrument method's behavior has been changed
Description
The behavior of methodSynthesizer.remapInstrumentwas not fully defined. There was no ability for the Synthesizer implementation to avoid instrument remapping support. Instrument remapping is very rarely used.TheSynthesizer.remapInstrumentimplementation did not work.Due the change, behavior of the
remapInstrumentmethod of theSynthesizerinterface has been changed:
falseresult signals that the synthesizer does not support instrument remapping- if instrument "to" (which will be used instead "from" instrument) is not loaded into the synthesizer, an
IllegalArgumentExceptionwill be thrown.The JavaSound synthesizer implementation has been changed accordingly.
Consequence Without Action
Likely none.Existing code which uses the
Synthesizerinterface as a client will handle successful results as success, and failure (either "false" result orIllegalArgumentException) as failure.Existing code which implements the
Synthesizerinterface will not satisfy the spec, but in most cases old behavior will be handled correctly.Recommended Fix
In client applications, review failure handling inSynthesizer.remapInstrument. InSynthesizerinterface implementations, change failure notification to satisfy the spec.Further Reading
2.1.7 Beans
Better EventHandler documentation and argument checking
Description
The documentation forjava.beans.EventHandlerhad two problems. Previously it did not completely describe what theeventPropertyNameargument does, and it did not document what the behavior was for invalid arguments. The documentation has been enhanced to describe clearly theeventPropertyNameargument, and thecreate()methods and the constructor have been modified to throwNullPointerExceptionfor null arguments.Consequence Without Action
NoneRecommended 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 ofCompositeType.isValuehave changed slightly. It will accept aCompositeDatathat has all the items in theCompositeType, plus some extra items. Previously, extra items were not allowed.Consequence Without Action
Note that such aCompositeDatawill work correctly with code that expects just the items listed in theCompositeType.Recommended Fix
No updates to existing code are required.Further Reading
MBeanServerInvocationHandler no longer forwards Object methods to MBean
Description
An MBean proxy created withMBeanServerInvocationHandler.newProxyInstancewill no longer forward the methodstoString(),hashCode(), andequals(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
- It defined an MBean with an operation
toString,hashCode, orequals, and accessed it through an MBean interface that does not mention those methods. This is highly unlikely. All MBean operations must be in the MBean interface. Otherwise extra implementation work will be needed to make the MBean behave correctly. It is rare to define an MBean with operations that look like methods fromObject.
- It depended on these methods being forwarded to the remote MBean and an exception being thrown because they are not defined as operations on that MBean. This is also very unlikely, and is greatly outweighed by the chances that the existing behavior will cause new code to fail because it expects proxies to behave rationally.
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 methodTimer.getNotificationIDs(String type)is specified to return aVectorofIntegerobjects. But the implementation previously returned aVectorofTimerNotificationobjects.Consequence Without Action
Existing code calling this method could get aClassCastException.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 toVectorinstead ofVector.Further Reading
NotificationBroadcasterSupport behavior changed when a NotificationFilter throws an exception
Description
WhenNotificationBroadcasterSupportis sending a Notification to a set of listeners, and theNotificationFilterassociated with one of those listeners throws aRuntimeException, 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
DescriptorSupportnow implementsequalsandhashCodesuch that two instances are equal if they have the same contents. Previously it inherited the default behaviour of these methods fromObject, so two instances were equal only if they were identical.Consequence Without Action
Theequalsmethod call for two instances ofDescriptorSupportthat 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 theequalsmethod.Further Reading
JMX Descriptor.getFieldValues spec was broken when descriptor empty
Description
The classDescriptorSupportpreviously interpreted some text in the Descriptor spec literally, such that an empty Descriptor would always return an empty array fromgetFieldValues(stringArray), rather than an array ofstringArray.lengthvalues (possibly null) as for any non-empty Descriptor. The previously specified behavior was likely to result in an unexpectedArrayIndexOutOfBoundsExceptionin 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 withstringArray.lengthvalues (possibly null) instead of an emptystringArray.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 returnedstringArraywithstringArray.lengthvalues that are possibly null.Further Reading
Allow UNKNOWN as impact value for OpenMBeanOperationInfo
Description
The result ofOpenMBeanOperationInfoSupport.getImpact()can now beMBeanOperationInfo.UNKNOWN, consistent with other types of MBeans.Consequence Without Action
if-then-elseorswitch-caseclauses in existing code handling Open MBeans may skip theUNKNOWNimpact (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 theUNKNOWNimpact value.Further Reading
Query.{initial|any|final}SubString no longer interprets wildcards
Description
The methodsinitialSubString,anySubString, andfinalSubStringinjavax.management.Querypreviously allowed the substring in question to contain wildcards. For example,Query.initialSubString(Query.attr("X"), "a*b")would returntrueif the value of theXattribute 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
Xbegins with the exact three characters "a*b".Consequence Without Action
Existing queries relying on the '*' and '?' characters being considered as wildcards ininitialSubString,anySubString, andfinalSubStringthat used to evaluate totruewill now evaluate tofalse.Recommended Fix
To perform a wildcard match, add an extra * at the end forinitialSubString, at the beginning forfinalSubString, and at both ends foranySubString. For example,Query.match(Query.attr("X"), "a*b*").Further Reading
Attribute type check was too restrictive in RequiredModelMBean.getAttribute
Description
RequiredModelMBean.getAttributepreviously 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 exceptionjavax.management.InvalidAttributeValueExceptionfor 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 exceptionjavax.management.InvalidAttributeValueException.Further Reading
RequiredModelMBean.setAttribute throws exception if no setMethod
Description
An application will see a change in behavior only if it defines agetMethodbut not asetMethodfor 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, orStringMonitor) had its own thread. The Monitor's calls toMBeanServer.getAttributeto 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 propertyjmx.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., thatgetAttributewould 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 injava.lang.managementhas an attributeHeapMemoryUsageof typeMemoryUsage. To monitor the amount of used memory as described by theusedproperty ofMemoryUsage, you could monitorHeapMemoryUsage.used. The stringHeapMemoryUsage.usedwould be the argument toMonitor.setObservedAttribute.Consequence Without Action
A string of the forma.bnow has a special meaning in the Monitor service. This will only affect existing code if it monitored an attribute whose name contained a dot (likea.b) and that attribute was not declared in the MBean's MBeanInfo.Recommended Fix
Declare thea.battribute 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 asjava.lang.Integerandjava.lang.Boolean, but does not include the primitive types such asintandboolean. When the type isIntegerorBooleanthere is no great difference to a client, because reflection treats this the same asintorboolean. However, when it isInteger[]orBoolean[]it is inconvenient and inefficient. All we are really interested in is arrays of primitive types. There is no difference betweenintandIntegerwhen they are the type of an attribute, parameter, or return value. Anintwill be wrapped as anIntegeranyway since everything is happening through reflection. On the other hand, there is a difference betweenint[]andInteger[].int[]is considerably more efficient in space and time, but is not currently expressible as an OpenType. So the idea here has been to extendArrayTyperather thanSimpleTypesuch that you can describeint[], 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 likeint[]. A J2SE 1.5 client will not see this in the correspondingArrayType, so it will seeInteger[]instead ofint[]. This may cause it to misbehave. Because previous versions of the API lack the newprimitiveArrayboolean field, they will deserialize anint[]as anInteger[]. This will often work (for example if arrays are read usingjava.lang.reflect.Array) but will occasionally causeClassCastExceptions. This only applies to "generic" (model-neutral) clients, since models that useint[]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 classjava.lang.reflect.Arrayto avoid possibleClassCastExceptions.Further Reading
CompositeDataSupport.equals now compares arrays element-by-element
Description
If you callcd1.equals(cd2), wherecd1is aCompositeDataSupportandcd2is an object implementingCompositeData(i.e., anotherCompositeDataSupport), and ifcd1andcd2have the sameCompositeTypethat includes at least one item of typeArrayType, 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
CompositeDataSupportobjects both haveArrayTypevalues, and the two values are different objects but equal, it will returnfalseif calling the methodequalsfrom J2SE 1.5 or earlier, but gettruefrom 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 defaultContent-Typefield. This caused problems for applications that were not expecting aContent-Typeto be set. However, applications that depend on the default setting ofContent-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 toStandardMBeanhas acquired a type constraint:
<T> StandardMBean(T impl, Class<T> intf)Consequence Without Action
Generification of the two-argument constructor toStandardMBeanmeans that if the second parameter is a class literal such asSomethingMBean.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
StandardMBeanline 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.StandardMBeanRecommended Fix
The fix is either to change the declaration ofimplfromObjecttoSomethingImplorSomethingMBeanor 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 theModelMBeanInfoto describe the MBean itself, and to the variousModelMBean*Infoclasses (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
OpenMBeanParameterInfoSupportthat adds an extra Descriptor parameter can potentially create ambiguity.Consequence Without Action
The addition of the new constructor toOpenMBeanParameterInfoSupportmeans 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
defaultValueis 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:
FollowReferencesfunctionIterateThroughHeapfunction- associated callbacks, structs, enums, and constants.
Added Other Functions:
RetransformClasses
Description: Support dynamic transformation (including instrumentation) of classes. Use this instead ofRedefineClassesto allow multiple agents and to permit instrumentation to be easily added and removed from classes.
Further Reading: See the JVM TI spec sections on Byte Code Instrumentation andRetransformClasses
ForceEarlyReturn*functions.
Description: Allow an agent to force a method to return prematurely. Allows a debugger user a limited amount of changing of the program counter.
Further Reading: CR 6216027
GetOwnedMonitorStackDepthInfo
Description: Determine stack frames in which monitors have been locked. Allows an agent to show the stack frames in which owned monitors have been locked. Can be used to display information deadlocks.
GetCurrentThread
Description: Get the current thread. This allows an agent callback to get thejthreadof the thread that is running the callback.
AddToSystemClassLoaderSearch
Description: Extend the search done by the system class loader. This allows instrumentation classes to be loaded by the system class loader. Use this if you need to put your instrumentation classes on the system classpath
GetConstantPool
Description: Retrieve the constant pool of a class. This allows access to the raw constant pool and all the data in it, for example annotations and class hierarchy information.
GetClassVersionNumber
Description: Get the version information for a class. Companion toGetConstantPoolsince the constant pool is class file version dependent.
Further Reading: CR 6263980
SetNativeMethodPrefixandSetNativeMethodPrefixes
Description: Support Java programing language instrumentation of native methods. An agent should use this if it wants to 'instrument' entries/exits of native methods.
Further Reading: CR 6263317
IsModifiableClass
Description: Determine if a class can be redefined/retransformed. In some cases, an implementation might not be able to redefine/retransform a class. Check this for each class to be redefined/retransformed.
Further Reading: CR 6306942, JVM TI specification
- Allow
AddToBootstrapClassLoaderSearchbe used in live phase.
Description: Needed for the new dynamic attach capability.
Added Events:
ResourceExhaustedEvent ()
Description: Determine when system resources (e.g., memory) are exhausted. An agent should use this to detect out of memory situations
Further Reading: CR 6456617
New JVM TI capabilities of the Java SE HotSpot virtual machine
- Allow the addition (or removal) of
private finallorprivate staticmethods via redefine/retransform. This allows native method prefixes to be applied to loaded classes.
Description: A small increase in the capability of redefine/retransform. Agents should be enhanced to allow such modifications
- Allow redefine and retransform of shared classes.
Description: An enhancement to redefine/retransform classes. Agents should be modified to support this new feature.
Further Reading: CR 6404550
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 thetoString()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):
- 4012001:
ACC_Abstractrequired for interfaces when version >= 50- 4293149, 6383849: Stop relaxed access checking for classes in the same package with local classloader for when version >= 49
-XX:+RelaxAccessControlChecksreverts to old behavior- 5060487: Only allow call of protected constructor by instances of a subclass (also backported to 5.0u9 and 1.4.2_12)
- 6324107: Deprecate
APIsDisallowmethod with no code attribute- 6339875: Disallow definition of classes in the
java.*packages. Already enforced byClass.defineClass()calls which take a name. Closed the loophole forJNI_DefineClass()and theClass.defineClass()with no name argument.- 5031222: Removed
JDK1_1InitArgsstruct fromjni.h. Continue to useJavaVMInitArgs.6253381: -Xcheck:jni JNI call made with exception pending should be a warning
Additional debugging capability of JNI applications. A side effect is that if an exception is taken while in the VM, with a pending exception, the VM will discard the pending exception, and the new exception will be thrown.
6444959/6374692: NullPointerException without user code in stack trace when running under N1 Grid Engine 6.0u8
- Patch 118855-15+ for S10_x86
- Users of JNI invocation APIs: use workaround suggested in 6374692
(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 bygraphics2d.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
InternalEnumPersistenceDelegatewill be used instead of the user's custom persistence delegate forEnumsubclasses.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:
- Fixed default behavior of persistence delegate to avoid security problem. Now XMLEncoder works with installed SecurityManager (for example, under Java Web Start).
- Fixed persistence delegate for
Mapto encode null entries in it.- Fixed encoding of string with illegal XML characters.
- Fixed problem with generation of property names in Turkish locale.
- Fixed encoding of the container with border layout.
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 timeConsequence Without Action
NoneRecommended 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 j
avax.management.openmbean.OpenType, the mutableALLOWED_CLASSNAMESstring array has been deprecated and a new unmodifiable string listALLOWED_CLASSNAMES_LISTshould be used instead.@Deprecated
public static final String[] ALLOWED_CLASSNAMESinstead use
public static final List<String> ALLOWED_CLASSNAMES_LIST2.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:
IterateOverObjectsReachableFromObjectIterateOverReachableObjectsIterateOverHeapIterateOverInstancesOfClassDeprecated Function types:
HeapObjectCallbackHeapRootObjectCallbackStackReferenceObjectCallbackObjectReferenceCallbackDeprecated Types:
jvmtiHeapObjectFilter- Heap Object Filter EnumerationjvmtiHeapRootKind- Heap Root Kind EnumerationjvmtiObjectReferenceKind- Object Reference EnumerationjvmtiIterationControl- Iteration Control Enumeration2.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 anObjectName. 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 ajobject. This can help with ensuring that appropriateDeletesare called so that memory is freed.Further Reading
Improved diagnostics
Description
Added DTrace probes to the VM to improve diagnosticsNow on Solaris 10 and later, DTrace is being ported to other platforms
Further Reading
- DTrace portal: http://www.sun.com/bigadmin/content/dtrace
- DTrace manual: http://docs.sun.com/app/docs/doc/817-6223
- Details of probes in JavaSE VM http://blogs.sun.com/roller/page/kamg?entry=built_in_dtrace_probes_in
- Example scripts for Java http://blogs.sun.com/roller/page/kamg?entry=example_dtrace_scripts_for_hotspot
- Converting djvm DTrace probes to 6.0 DTrace probes http://blogs.sun.com/roller/page/kamg?entry=djvm_to_hotspot_6_0
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 notjava.util.concurrentlocks.Consequence Without Action
None. In JDK 6,java.lang.management.ThreadInforeports the monitor lock orjava.util.concurrentownable synchronizer that a thread is blocked or waiting on without any code modification.Recommended Fix
Use the new API to obtain information aboutjava.util.concurrentownable synchronizers.Further Reading
- CR 5086470
- http://java.sun.com/javase/6/docs/technotes/guides/management/enhancements.htmll
java.util.concurrent.locks.AbstractOwnableSynchronizerjava.lang.management.ThreadMXBean.isObjectMonitorUsageSupportedmethodjava.lang.management.ThreadMXBean.isSynchronizerUsageSupportedmethodjava.lang.management.ThreadMXBean.findDeadlockedThreadsmethod
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 inThreadInfoobjectsRecommended Fix
Use the newdumpAllThreadsorgetThreadInfomethods in order to obtain owned locks information.Further Reading
- CR 6215270
- http://java.sun.com/javase/6/docs/technotes/guides/management/enhancements.html
java.lang.management.ThreadMXBean.dumpAllThreadsmethodjava.lang.management.ThreadMXBean.getThreadInfo(long[], boolean, boolean)methodjava.lang.management.LockInfoclassjava.lang.management.MonitorInfoclass
API to get system load average
Description
New ability to get system load averageRecommended 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
- CR 6336608
- http://java.sun.com/javase/6/docs/technotes/guides/management/enhancements.html
java.lang.management.OperatingSystemMXBean.getSystemLoadAveragemethod
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 orjconsoleto access the HotSpot enhanced diagnosability.Further Reading
- CR 6283436
- CR 6314913
- http://java.sun.com/javase/6/docs/jre/api/management/extension/index.html
- http://java.sun.com/developer/technicalArticles/J2SE/monitoring/
- http://java.sun.com/javase/6/docs/technotes/tools/share/jconsole.html
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 propertiesRecommended Fix
Use the new API to develop a tool that dynamically attaches to a running VM.Further Reading
- CR 6173612
- http://java.sun.com/javase/6/docs/technotes/guides/attach/index.html
- http://blogs.sun.com/alanb/entry/late_binding_agents_and_fun
New JConsole plugin API (com.sun.tools.jconsole API)
Description
Provide ajconsoleplug in interface for the user to define custom tabs.Further Reading
- CR 6179281
- http://java.sun.com/javase/6/docs/jdk/api/jconsole/spec/index.html
- http://java.sun.com/javase/6/docs/technotes/tools/share/jconsole.html
JTopDemo under the<JDK6>/demo/management/JTopdirectory- Scripting console demo under
<JDK6>/demo/scripting/jconsole-plugindirectory
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.htmlList<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.eventsevents:MonitorContendedEnterEvent MonitorContendedEnteredEvent MonitorWaitEvent MonitorWaitedEventNew
com.sun.jdi.requestrequests:MonitorContendedEnterRequest MonitorContendedEnteredRequest MonitorWaitRequest MonitorWaitedRequestNew 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
TheButtonGroupclass is used to create a mutual-exclusion scope for a set of buttons. Initially all buttons in aButtonGroupare 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 toButtonGroup.Further Reading
New constants for javax.swing.Action interface
Description
Swing'sActioninterface lacked some of the abilities provided bybutton. Most notable is the ability for theActionto have a selected state. In addition to fixing multiple inconsistancies in how various components support Actions the following new constants have been added toAction:
Action.SELECTED_KEY
When anActionis associated with a button that visually represents a selection, likeJCheckBox, the selected state of the button is mirrored from theAction. Any changes to the selected state of the button are pushed to theAction, and vice versa.
Action.LARGE_ICON_KEY
Prior to JDK 6, all buttons (including menus) would set their icon from theSMALL_ICONproperty. In JDK 6, buttons first looks forLARGE_ICON_KEY.If the value is non-null, it is used as theIcon. If the value ofLARGE_ICON_KEYis null, the value fromSMALL_ICONis used. Menus only useSMALL_ICON. This allows menus and buttons using the sameActionto have differentIcons.
Action.DISPLAYED_MNEMONIC_INDEX_KEY
Can be used to specify the index at which to visually represent the mnemonic.In addition, the new method
setHideActionTexthas been added toAbstractButton. This method allows you to control whether or not the text of the button should come from theAction. 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 inJTabbedPanecould only contain an icon, text and/or html. Three new methods have been added toJTabbedPaneto allow adding components as labels to tabs in aJTabbedPane,setTabComponentAtgetTabComponentAt, andindexOfTabComponent.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:
- 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.
- 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:
- An API was added allowing developers to specify one of a handful of new drop modes on components supporting drops.
JList,JTable,JTreeandJTextComponentnow have asetDropMode()method that takes a newDropModetype. 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.- Overloaded versions of two methods,
canImport()andimportData()have been provided inTransferHandlerthat take aTransferInfoobject 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 toTransferHandlerto allow for further customization of when to show the drop location.- The internal implementation of Swing DnD was re-designed to reduce the number of classes and get rid of the exceptions.
Further Reading
- CR 4468566
- CR 4942851
- CR 6277499
- CR 6315298
- CR 6331837
- CR 6344471
- CR First Class Drag and Drop Support in JDK6
- CR Location-Sensitive Drag and Drop in JDK6
- CR Top-Level Drop with Swing and Java SE 6
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):
- CR 6184866:
BasicTreeUIshould usefactorymethod to construct drop target listener- CR 6184817: Make
BasicDropTargetListenerpublic- CR 4468566: Swing DnD should not use selection to show drop location
- CR 4760426:
JTreeDnD conflicts withJTree.setUI(..)- CR 5029427: Location sensitive dropping
- CR 5029432: Provide a way of getting the action in
TransferHandler.importData(...)
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 SwingTransferHandler, which was designed to simplify DnD in Swing, did not support this.setTransferHandlerandgetTransferHandlermethods were added toJFrame,JDialog,JWindowandJAppletto 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 thejavax.swingpackage.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 newprint()methods and one newgetPrintable()method were added toJTextComponentto 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 methodsgetBaseline()andgetBaselineResizeBehavior()have been added tojava.awt.Component.JComponentoverrides these and forwards to the appropriate UI classes. The UI classes override these methods to return the baseline.GridBagLayoutandFlowLayouthave 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.LayoutManagerscan use this class to determine the ideal amount of space to place between components. Look and feel authors can provide a customLayoutStyleby way of overriding theLookAndFeelmethodgetLayoutStyle().Further Reading
Addition of a GroupLayout LayoutManager
Description
A new layout manager,GroupLayout, has been added to thejavax.swingpackage. ThisLayoutManager, 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 usingJTablerequire sorting and filtering. Sorting and filtering APIs were added toJTable. Sorting can now be enabled by specifying aRowSorteronJTable. 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, thusFrameis 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-splashor by specifying a splash image in a jar file which is executed with-jaroption.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 methodsMouseEvent.getLocationOnScreen(),MouseEvent.getXOnScreen(), andMouseEvent.getYOnScreen()can now be used to obtain absolute coordinates on the screen fromMouseEvent.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 theFrame, 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 forFramesbut not forDialogs, 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 toWindowto allow setting multiple icons for bothFramesandDialogs.Further Reading
API to launch desktop helper applications
Description
Every modern desktop provides some common services, such as a browser, mailer and editor. New classjava.awt.Desktophas been added to provide access to these services.Further Reading
2.6.6 I18N
java.util.ResourceBundle improvements
Description
java.util.ResourceBundlehas been improved so that applications can control thejava.util.ResourceBundle.getBundlebehavior. Refer tojava.util.ResourceBundle.getBundleandjava.util.ResourceBundle.Controldocumentation.Further Reading
Rounding modes in java.text.NumberFormat
Description
java.text.NumberFormatnow supports rounding modes. Refer to thejava.text.NumberFormat.setRoundingModedocumentation.Further Reading
New constructor in java.util.PropertyResourceBundle
Description
The newjava.util.PropertyResourceBundleconstructor takes ajava.io.Readerso that properties files in any encoding can be read. Refer to thejava.util.PropertyResourceBundle(java.io.Reader)documentation.Further Reading
Extendable java.text.CollationKey
Description
java.text.CollationKeyis 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@ConstructorPropertieswas 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 constructorDefaultPersistenceDelegate(String[] constructorPropertyNames)does. Defining the annotation removes the need to code aDefaultPersistenceDelegateexplicitly, and it is useful outside thejava.beansframework.Consequence Without Action
NoneRecommended Fix
IfDefaultPersistenceDelegateis registered withXMLEncoderfor your class each time, you can replace all such usages with the annotation@ConstructorPropertiesbefore 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
SomethingMXBeanand a Java class that implements that interface. Every method in the interface defines either an attribute or an operation in the MXBean. The annotation@MXBeancan 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 injava.lang.management.The key idea behind MXBeans is that types such as
java.lang.management.MemoryUsagethat are referenced in the MXBean interface,java.lang.management.MemoryMXBeanin this case, get mapped into a standard set of types, the Open Types that are defined in the packagejavax.management.openmbean. The exact mapping rules appear in the MXBean specification, but to oversimplify we could say that simple types likeintorStringare unchanged, while complex types likeMemoryUsageget mapped to the standard typeCompositeDataSupport.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 forOpenMBean *InfoSupport. TheMBean*InfoandOpenMBean *InfoSupportclasses now contain agetDescriptor()method.Open MBeans return information about default and legal values from the
getDefaultValue(),getLegalValues(),getMaxValue(), andgetMinValue()methods ofOpenMBeanParameterInfoandOpenMBeanAttributeInfo. 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
DescriptorKeycan 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
@Unitsthat 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.JMXclass.
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 thejavax.management.JMXclass, passing it the MBean's MBeanServerConnection, object name, the class name of the MBean interface andtrue, 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 ofnewMBeanProxy().Add ObjectName constants to JMX API
public static final ObjectName javax.management.MBeanServerDelegate.DELEGATE_NAMEDefines the default
ObjectNameof theMBeanServerDelegate.public static final ObjectName javax.management.ObjectName.WILDCARDDefines the wildcard "*:*"
ObjectName.Support key=* wildcard in
ObjectName
ObjectNamewildcards in keys:In J2SE 1.5 you could say
domain:key1=value1,*to match MBeans that havekey1=value1in their name, but notdomain:key1=*to match MBeans that havekey1in their name.The
ObjectNamefunctionality has been extended in Java SE 6 such that you can put a wildcard (* and/or ?) anywhere in a value, e.g.,key=a*bas well askey=*. 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
Thejavax.imageiopackage 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.
java.awt.LinearGradientPaintis a more flexible version ofGradientPaintthat allows for multi-stop gradients involving two or more colors.
java.awt.RadialGradientPaintis similarly flexible, except instead of interpolating the colors in a linear fashion, the colors radiate out from a center point (imagine ripples expanding from a drop of water).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
Thejava.awt.geom.GeneralPathclass 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.GeneralPathis now an empty subclass ofPath2D.Float.Applications which want to use double precision coordinates must use the new
Path2D.Doubleclass. Applications which do not need this precision can continue to useGeneralPathor can use the newPath2D.Floatclass.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 hintjava.awt.RenderingHints.KEY_TEXT_ANTIALIASING. The most important of these new values arejava.awt.RenderingHints.VALUE_TEXT_ANTIALIAS_GASP(the equivalent to the Windows "Standard Font Smoothing" Setting) andjava.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.desktophintsand set it on theGraphicsinstance 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 forjava.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 withjava.awt.Font.createFont()previously were not available toFontconstructors. 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 newFontconstructors. 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 asFontattributes 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 ofjava.awt.font.TextAttributefor more information.
Path2D: New hit testing facil