Java
Java SE
![]() |
JDK TM 6 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.2 Source Incompatibilities
2.3 Dependencies on Implementation Mechanisms
2.4 Deprecated APIs
2.5 Reserved Keywords
2.6 New Features or APIs of Note During Migration3 Deployment and Configuration Issues
3.1 New or Changed Configuration Properties
3.2 New Command Line Tool Arguments
3.3 New Developer Tools that Replace Old Ones
3.4 Changed Developer Tool Defaults/Behaviors
3.5 Newly Supported Platform Behaviors
3.6 Other4 Tools and Platform Developer Issues
4.1 Class File Format Changes
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 a code>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
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 andRetransformClassesForceEarlyReturn*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 6216027GetOwnedMonitorStackDepthInfo
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 6263980SetNativeMethodPrefixandSetNativeMethodPrefixes
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 6263317IsModifiableClass
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 /p>
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
javax.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, code>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 facilities
Description
The newjava.awt.geom.Path2Dclass provides new static methods to calculate the results for hit testing from the path description supplied by aPathIterator. Developers who create their own custom implementations of theShapeinterface can use these new methods to implement the 6 hit testing methods that are required by theShapeinterface as long as they provide a valid implementation of thePathIteratorinterface. For example, if you have a classMyShapewhich implements theShapeinterface, then you can use a code template similar to the following to compute the results of any of the hit testing methods:public boolean contains(double x, double y) { return Path2D.contains(getPathIterator(null), x, y); }Further Reading
See the documentation of the following methods in thejava.awt.geom.Path2Dclass:Path2D.contains(PathIterator pi, double x, double y) Path2D.contains(PathIterator pi, Point2D p) Path2D.contains(PathIterator pi, double x, double y, double w, double h) Path2D.contains(PathIterator pi, Rectangle2D r) Path2D.intersects(PathIterator pi, double x, double y, double w, double h) Path2D.intersects(PathIterator pi, Rectangle2D r)
Many geometry classes are now Serializable
Description
Most of the leaf classes in thejava.awt.geomclasses are now Serializable. Note that only theFloatandDoubleleaf subclasses have been made Serializable, but the abstract base classes likeRectangle2D,Ellipse2D, et al, are not Serializable by default. Specifically, the following classes are all now Serializable:java.awt.geom.Rectangle2D.Float java.awt.geom.Rectangle2D.Double java.awt.geom.RoundRectangle2D.Float java.awt.geom.RoundRectangle2D.Double java.awt.geom.Ellipse2D.Float java.awt.geom.Ellipse2D.Double java.awt.geom.Arc2D.Float java.awt.geom.Arc2D.Double java.awt.geom.Path2D.Float java.awt.geom.Path2D.Double java.awt.geom.GeneralPath java.awt.geom.Point2D.Float java.awt.geom.Point2D.Double java.awt.geom.Line2D.Float java.awt.geom.Line2D.Double java.awt.geom.QuadCurve2D.Float java.awt.geom.QuadCurve2D.Double java.awt.geom.CubicCurve2D.Float java.awt.geom.CubicCurve2D.DoubleRequired Action
There is one known incompatibility caused by the changes to make these classes Serializable. Since theArc2Dclass does not contain a publicly accessible constructor with no arguments, if a program has declared a Serializable subclass of eitherArc2D.FloatorArc2D.Doublethen it will no longer compile against JDK 6. The only workaround is to not declare any such subclasses Serializable. Since theFloatandDoublesubclasses are already Serializable themselves then it is no longer necessary for such a subclass to be declared Serializable any more.Further Reading
See the documentation of the Serialized Form of each class. Also note the following CR for more information on the problem described in the Required Action section:
2.6.10 Core Libraries
Additional compressed streams added
Description
java.util.zip.{DeflaterInput, InflaterOutput}Streamclasses were added to JDK 6. The new streams can improve some existing code where applications need to send compressed data over a network as packets or via a third party API.DeflaterInputStreamis an input stream that compresses data while it is being read.InflaterOutputStreamis the corollary, an output stream that decompresses data while it is being written.Consequence Without Action
The new APIs eliminate the current need for additional code.Further Reading
Improved interactive console I/O
Description
There are strong requests to have agetpass(3C)-like functionality on the Java platform to get sensitive user keyboard input (such as a password/passphrase) without echoing. This long-awaited feature is now provided by the newjava.io.Consoleclass.Another feature of
java.io.Consoleis that this class uses the encoding/codepage used by the underneath native console, instead of the JVM default encoding, when dealing with the input/output stream. This is particularly useful when the encoding used by the native console is different to the JVM default encoding, which is a normal scenario on Windows platforms.Further Reading
Properties class now includes character based stream interface
Description
The load/store facility ofjava.util.Properieshas been expanded to deal with character based stream Reader/Writer interface. This brings thePropertiesuser two major benefits:
- Support of non-8859-1 encoding (mainly UTF8) for the
Propertyfile used inProperyResourceBundleclass. See CR 4919638.- When the persistent storage behind the
InputStream/OutputStreamis a character based (i.e., the primitive typechar) interface, the application no longer needs to convert back and forth between acharstream and ISO8859-1 byte stream.Further Reading
Ability to manipulate file access attributes in File class
Description
A set of access permission manipulating methods have been added injava.io.Fileto address the need to allow reading and writing of simple file attributes, such as the permissions associated with the Unixchmodcommand and the ownership information associated with the Unixchgrpandchowncommands.Further Reading
File.canExecute()File.setExecutable(boolean)File.setExecutable(boolean, boolean)File.setReadable(boolean)File.setReadable(boolean, boolean)File.setWritable(boolean)File.setWritable(boolean, boolean)
Method for discovering free disk space
Description
New methods were added for discovering the amount of free disk space, in bytes, in the filesystem partition named by a givenjava.io.Fileinstance.Consequence Without Action
No method for discovering the amount of free space.Further Reading
java.util.concurrent updates
Description
4137464: (coll) TreeMap should have bi-directional iterator
A new interface to support double-ended queue operations calledDequehas been added.
ExtendedSortedSet/SortedMapinterfaces toNavigableSet/NavigableMapinterfaces, providing bidirectional navigation.
A large number of extantjava.utilandjava.util.concurrentbugs and rfes are fixed.
Here's the list of the bugs being addressed:
4155650 : (coll) Sorted Collection Classes with bidirectional navigation
4216399: (coll) TreeMap: please make getCeilEntry and get PreviousEntry >>public<<
4294891: (coll) Add "next/previous" to both SortedMap and SortedSet
4521038: (coll spec) Clarify that ArrayList.contains uses "equals"
4802637: (coll) Minor change to TreeMap.getEntry comparison code for performance
4904074: (coll) Provide basic Map.Entry class
4942830: (coll spec) TreeSet.remove - absence of Compara{ble,tor} throws ClassCastException
5018254 : (coll) 'remove' operation fails in tailMap of a null-key-allowing TreeMap
5018849: (coll) TreeSet.contains(null) does not agree with Javadoc
5048399: (coll) please fix anachronisms in collections internal generification
5073546 : Minor ConcurrentHashMap constructor spec tweaks
5108057: Small Error in JavaDoc for method isEmpty of ConcurrentLinkedQueue
6192476: CopyOnWriteArraySet.iterator should explicitly say it uses list order
6192552: Deques
6207928: ReentrantReadWriteLock provides no way to tell if current thread holds read lock
6207984: (coll) PriorityQueue.remove(Object o) will remove an object with the same priority as o
6233235 : Add allowCoreThreadTimeOut to ThreadPoolExecutor to optionally allow core thread to use keep-alive
6233236: Reduce need to replace interrupted worker threads in ThreadPoolExecutor for performance
6236036: Timeouts can cause garbage retention in lock classes
6245166: (coll spec) TreeMap class documentation should use SortedMap instead of Map
6247907: Interruptions and ThreadPoolExecutor.runTask
6261984: (coll spec) *List collections doc fixes
6264015: Performance improvement to Exchanger and SynchronousQueue
6264242: (coll spec) foo(E o) -> foo(E e)
6268068: (coll) PriorityQueue.remove(Object) should use equals, not its ordering, to find element to remove
6269146: Cancelled FutureTask's interrupt bit not always set
6269713: (coll) Unchecked exception specifications of collection classes are missing or inaccurate
6269720: (coll spec) Improve documentation of "natural ordering"
6269729: Improve method tables in BlockingDeque and related interfaces
6269739: BlockingQueue.drainTo needs to throw all unchecked exceptions that Collection.add does
6269785: ConcurrentMap.replace,remove methods "equivalent" code not correct when elt not in map
6271387: (coll spec) toArray method javadocs are inaccurate
6277663: Improve extensibility of thread pools
6281487: ReentrantReadWriteLock: readers repeatedly acquire lock while writer is waiting
6282140: CopyOnWriteArrayList maintenance
6294770: java.util.concurrent.locks.ReentrantReadWriteLock acquisition order
6301085: (coll) Add Collections.asLifoQueue(Deque)
6305337: Reentrant writeLock in Fair mode ReentrantReadWriteLock may block
6312056: ConcurrentHashMap.entrySet().iterator() can return entry with never-existent value
6314788: Tasks resubmitted to a ThreadPoolExecutor may fail to execute
6315709: Reentrant writeLock in Fair mode ReentrantReadWriteLock may block
6272521: ConcurrentHashMap.remove(x,null) might remove x
Further Reading
IEEE 754 Recommended Functions to Math and StrictMathDescription
New basic low-level methods for manipulating floating-point values, e.g. "extract exponent." have been added toMathandStrictMa th.The new methods added are
copySign(),getExponent(),nextAfter(),nextUp(),scalb()forf loatanddoublearguments to theMathandStrictMathclasses. In addition, constants forMIN_NORMAL,MAX_EXPONENT, andMIN_EXPONENTare added toFloatandDouble.Consequence Without Action
The new APIs eliminate the current need for additional code.Further Reading
2.6.11 Networking
Default CookieManager implementation
Description
This enhancement improves on the CookieHandler API introduced in J2SE 1.4, by providing a default implementation ofCookieHandler, which will remove the need to implementCookieHandlerin the application.Further Reading
Programmatic access to network parameters
Description
This enhancement improves the amount of information that can be acquired fromNetworkInterfaceinstances. The additional information that be acquired includes Broadcast address, Subnet mask, Mac/hardware address, MTU size, and State (up/down).Further Reading
2.6.12 Java Compiler
Description
The compiler, javac, now includes annotation processing replacing the functionality of the command line tool apt. A guide is under way and will be announced on http://java.sun.com and http://forum.java.sun.com/forum.jspa?forumID=514.Further Reading
Description
The compiler can be called from a program using the features ofjavax.tools. Some applications has previously used the compiler's unsupported internal data structures directly and can now use the interfaces incom.sun.source.*andjavax.lang.model.*Further Reading
JSR 175's java.lang.SuppressWarnings
Description
javacnow uses the annotations of typejava.lang.SuppressWarningsto suppress compiler warnings.Further Reading
This section is aimed at the Java deployer whose task it is to ensure the smooth deployment of an existing set of Java applications onto Java SE 6. It covers changes in the way the Java SE platform is mapped into the deployment environment, including installation, configuration and serviceability.
3.1 New or Changed Configuration Properties
3.1.1 Monitoring and Management
New out-of-the-box remote managment property
Description
A new management property,com.sun.management.jmxremote.registry.ssl, has been added to enable the use of an SSL-enabled RMI registry so that only legimate clients with the appropriate SSL certificates can obtain the connector stub.Consequence Without Action
The RMI registry is not SSL-enabled.Recommended Fix
Use this property for secure remote managementFurther Reading
- CR 6228231
- http://java.sun.com/javase/6/docs/technotes/guides/management/agent.html
- http://java.sun.com/javase/6/docs/technotes/guides/management/enhancements.htmll
3.1.2 Swing
New or changed configuration properties
A new system property,
swing.actions.reconfigureOnNull, has been added as part of cleaning up actions (see description onActionsin first section). This property is documented in thejavax.swing.Actionclass.Newly supported platform behaviors (i.e., Vista deployment defaults)
Swing's GTK and Windows Look and Feel now take advantage of the native system to do much of the rendering. As a result, the visual appearance of components better match their native counterpart, and are themeable to the same extent (and by the same mechanism) as the native system. Swing components are also Vista ready.
3.1.3 Core Libraries
The java.nio.channels.FileLock class checks for files already locked by other FileChannel instances
Description
Java SE 6 throws anOverlappingFileLockExceptionif an application attempts to lock a region that overlaps a region locked through anotherFileChannelinstance. Previous versions did not check for file locks obtained by otherFileChannelinstances.Java SE 6 has added the system property
sun.nio.ch.disableSystemWideOverlappingFileLockCheckto controljava.nio.channels.FileChannel.lockfile checking behavior, as follows:
- If this system property is set (or is set to some value other than
false) thenjava.nio.channels.FileChannel.lockchecks for overlapping file locks obtained using thisFileChannelinstance only. Locks acquired by otherFileChannelinstances to the same file are not checked.- If this system property is not set (or is set to the value
false) thenjava.nio.channels.FileChannel.lockchecks for overlapping file locks from allFileChannelinstances, according to the specification.The
sun.nio.ch.disableSystemWideOverlappingFileLockChecksystem property exists to provide compatibility with J2SE 1.4 and 1.5, which do not implement the JVM-wide overlapping file lock check.Consequence Without Action
By default thejava.nio.channels.FileChannel.lockmethod checks if the requested lock overlaps with a region held by this Java virtual machine.
Solaris-specific Hotspot switch UseVMInterruptibleIO
Description
On Solaris, thread interruption of a thread attempting certain I/O operations results in interruption of the operations and the throwing ofInterruptedIOExceptionin circumstances where thread interruption is ignored on Linux and Windows platforms. This Solaris-specific I/O interruption in response to thread interruption is enabled by default, as with previous releases, but is now controllable with the new Hotspot option switchUseVMInterruptibleIO. By default this switch will be enabled to maintain previous behavior. If the switch is turned off with-XX:-UseVMInterruptibleIO, the Solaris-specific I/O interruption in response to thread interruption will be disabled. The default setting of this switch may be changed to disabled during the early states of the next major Java SE release cycle (JDK 7) to boost port ability. If this change is made, the switch will be available subsequently to allow Solaris-specific behavior as required.Consequence Without Action
Thread interruption behavior on Solaris will be compatible with previous releases.Further Reading
3.2 New Command Line Tool Arguments
3.2.1 AWT
-splashadded to show splash screen.3.2.2 New VM Command Line Options
New Hotspot portal
The new Sun HotSpot Portal http://java.sun.com/javase/technologies/hotspot.jsp includes links to:
- HotSpot VM Comand Line Options
- Java Trouble-Shooting and Diagnostic Guide
- Performance and Tuning
- Performance Tools
Java launcher should create JVM from non-primordial thread
Description
There will be a release note on this as well as details under-Xssoption. (see above for HotSpot VM Command Line Options off of the HotSpot Portal). We can either leave it out of the Migration Guide or reference it and point them to the details elsewhere.Further Reading
Performance improvement via Biased Locking, with fall-back command-line option
Description
The Java programming language supports multithreaded programming at a very basic level via thesynchronizedkeyword. Using either synchronized methods or synchronized code blocks, any Java object may potentially be used as a synchronization construct, or a monitor.All modern Java virtual machine implementations (JVMs) optimize the inner workings of the
synchronizedkeyword using a technique called lightweight locking. The basic premise of this optimization is that most monitors are uncontended, meaning that only one thread attempts to enter the monitor at any given time. This property is true in most programs. Because of this property, it is possible to optimize the implementation of thesynchronizedkeyword for uncontended monitors to use only one or two atomic CPU instructions upon monitor entry and exit.On multiprocessor machines, such atomic instructions are relatively expensive and most computers currently shipping, even home computers, are multiprocessors. Research originally done by IBM showed that not only are most Java monitors uncontended, but they are typically acquired by only one thread during the object's lifetime. A new class of optimizations we call biased locking results from this observation. With such an optimization present, uncontended monitors can be entered and exited without using any atomic operations. This significantly reduces the cost of uncontended synchronization.
Biased locking is a relatively recent addition to JVMs and is still a relatively aggressive optimization. This means that some applications will see performance improvements, most may not see any performance difference, and some, hopefully few, applications may see performance degradation due to it. The optimization is enabled in the Java SE 6 release by default so applications can most easily take advantage of it. The following sections describe how to disable it if necessary.
The following bugs are related directly or indirectly to the introduction of biased locking and the bug reports may prove informational.
- 6264252 Improve uncontended synchronization performancev
- 6288464 Nightly testing failures with biased locking
- 6291058 JCK15a:javasoft.sqe.tests.vm.jvmti.gohc001.gohc00101.gohc00101 test fails with VM crash on Linux
- 6291370 hs101t004 and hs101t006 hang due to biased locking
- 6295591 Startup regression with biased locking
- 6298299 Bug in bias revocation in compiled synchronized native methods
- 6302798 Java2Demo assertion failure with biased locking
- 6304225 IE crashes with b44
libjvm.dll- 6306530 Preserved mark/oop stacks must be allocated from C heap in MarkSweep
- 6313317 JVM crashes when calling
AttachCurrentThreadandDetachCurrentThreadfrom concurrent native threads- 6357512 Scalability problems with biased locking
- 6392097 Reduce number of preserved marks when biased locking enabled
- 6410144 JDK6 JVM crashes with
-XX:-UseBiasedLocking- 6430224
BiasedLocking::preserve_marks()scales poorly, impacts GC pause times- 6434117 jdk1.5.0_08 core dumps when using
-XX:+UseBiasedLocking- 6445152 Biased locking broken for CMS scavenges
- 6458537 BiasedLocking causes 30% Performance regression in
SPECjAppServerConsequence Without Action
All Java applications will continue to execute correctly with the introduction of this optimization. If it is discovered that throughput or performance of an application running on Java SE 6 has degraded compared to Java SE 1.5, see the Recommended Fix section.Recommended Fix
If it is discovered that throughput or performance of an application running on Java SE 6 has degraded compared to Java SE 1.5, you may try disabling the biased locking optimization by passing the command line option-XX:-UseBiasedLockingto the JVM. If this works around the performance problem, please file a bug so that we can try to tune for such situations in the future.Further Reading
A paper on Sun's implementation of the biased locking optimization has been published in the proceedings of ACM OOPSLA 2006:Russell, K. and Detlefs, D. Eliminating Synchronization-Related Atomic Operations with Biased Locking and Bulk Rebiasing. In proceedings of ACM OOPSLA 2006.
Solaris-specific Hotspot switch UseVMInterruptibleIO
Description
On Solaris, thread interruption of a thread attempting certain I/O operations results in interruption of the operations and the throwing ofInterruptedIOExceptionin circumstances where thread interruption is ignored on Linux and Windows platforms. This Solaris-specific I/O interruption in response to thread interruption is enabled by default, as with previous releases, but is now controllable with the new Hotspot option switchUseVMInterruptibleIO. By default this switch will be enabled to maintain previous behavior. If the switch is turned off with-XX:-UseVMInterruptibleIO, the Solaris-specific I/O interruption in response to thread interruption will be disabled. The default setting of this switch may be changed to disabled during the early states of the next major Java SE release cycle (JDK 7) to boost portability. If this change is made, the switch will be available subsequently to allow Solaris-specific behavior as required.Consequence Without Action
Thread interruption behavior on Solaris will be compatible with previous releases.Further Reading
Hotspot Garbage Collectors
These are command line flags that have been added or changed in some way for 6.0.
ExplicitGCInvokesConcurrent
Description
ExplicitGCInvokesConcurrentis a new flag and is off by default. If it is turned on, with theUseConcMarkSweepGC, theSystem.gc()call will perform a concurrent collection instead of a stop-the-world collection.Further Reading
UseConcMarkSweepGC
Description
Use of theUseConcMarkSweepGCgarbage collector causes a different default heap configuration than in 1.5 and previous releases. The old default values were:
MaxNewSize = 4m per GC thread
NewRatio = 15
NewSize = 4m
MaxTenuringThreshold = 0
SurvivorRatio = 1024The new default values are:
MaxNewSize = 16 m per GC thread
NewRatio = 7
NewSize = 16m
MaxTenuringThreshold = 4
SurvivorRatio = <platform dependent>The platform dependent
SurvivorRatiovalue is not changed from those used by the other collectors if the new cms defaults are being used.The command line flag
CMSUseOldDefaultscauses the old defaults to be used if set totrue.Consequence Without Action
The default heap configuration for theUseConcMarkSweepGCgarbage collector will be different.Recommended Fix
No changes are normally necessary. If desired, use the flag-XX:+CMS UseOldDefaultsto use the old default values.Further Reading
UseGCOverheadLimit
Description
The command line flagUseGCTimeLimithas been replaced byUseGCOverheadLimit.UseGCTimeLimitwill be recognized in 6.0 but may be removed in a later release. If an out-of- memory exception is thrown as a result of the gc time limit, the detail message now readsGC overhead limit exceeded.Consequence Without Action
If the command line flagUseGCTimeLimitis used, a warning message will be printed giving the new name of the flagUseGCOverheadLimit.Recommended Fix
No changes are normally necessary. If desired, change to the use of the flagUseGCOverheadLimit.Further Reading
-Xincgc
Description
In Java SE 1.5, the command line flag-Xincgcwas the equivalent of-XX:+UseConcMarkSweepGC.In JDK 6 it is the equivalent of
-XX:+UseConcMarkSweepGC -XX:+CMSIncrementalMode.Consequence Without Action
The incremental mode ofUseConcMarkSweepGCwill be used.Recommended Fix
No changes are normally necessary. If desired, use the flag
-XX +UseConcMarkSweepGCin place of-Xincgcto revert to the old behavior of Java SE 1.5.Further Reading
Ignored flags
Description
The following flags previously associated with the train garbage collector (which was deprecated in Java SE 1.5) are ignored in JDK 6.
UseTrainGC
UseSpecialLargeObjectHandling
UseOversizedCarHandling
TraceCarAllocation
PrintTrainGCProcessingStats
LogOfCarSpaceSize
OversizedCarThreshold
MinTickInterval
DefaultTickInterval
MaxTickInterval
DelayTickAdjustment
ProcessingToTenuringRatio
MinTrainLengthConsequence Without Action
The flags are now ignored. Use of the flags will cause a warning message to be printed.Recommended Fix
Remove these flags from the command line.Further Reading
UseParallelOldGC
Description
UseParallelOldGCis a new flag and is off by default. TurningUseParallelOldGCon will invoke the use of a new parallel old generation garbage collector in conjunction with theUseParallelGCgarbage collector.Consequence Without Action
NoneRecommended Fix
No updates to existing command lines are requiredFurther Reading
CMSPermGenPrecleaningEnabled
Description
The flagCMSPermGenPrecleaningEnabledis on by default.Consequence Without Action
The low pause collector (-XX:+UseConcMarkSweepGC) will process the permanent generation during the precleaning phase.Recommended Fix
Turn off the flagCMSPermGenPrecleaningEnabledif this behavior is not desired.Further Reading
PrintGCDetails and PrintHeapAtGC output change
Description
The output produced by the flagsPrintGCDetailsandPrintHeapAtGChas changed. The output generated by these flags is used during product development and changes as garbage collection features are added or modified. The content and the format change regularly from release to release.Consequence Without Action
Parsing of the output from the flagsPrintGCDetailsandPrintHeapAtGCmay need to be changed.Recommended Fix
Change any parsing of the output from the flagsPrintGCDetailsandPrintHeapAtGCto accept the new format.
Initial size of the generations changed
Description
In order to reduce the JVM startup time, the initial sizes of the tenured generation and the young generation were increased on some platforms. The initial default tenured generation size has been increased to 4MB. On ia32 operating systems the initial default young generation size was increased to 1MB. On other platforms the young generation initial default size is already equal to or greater than 1MB.Consequence Without Action
The new initial sizes of the generations will be used.Recommended Fix
If you did not previously explicitly set sizes of young and old generations, no changes are necessary. Otherwise, explicitly set the initial sizes of the young generation and the tenured generation on the command line.Further Reading
Concurrent multiple GC threads
Description
With the low pause collector (-XX:+UseConcMarkSweepGC) in Java SE 1.5 and earlier releases, there was only 1 GC thread doing concurrent work. In JDK 6, additional GC threads may participate in the concurrent marking phase of the collection. One consequence of this change is that fewer cpu's may be available to the application during the concurrent marking phase. The number of additional GC threads that will be used depends on the number of cpu's on the machine. This feature is enabled by default. It can be turned off with the flagCMSConcurrentMTEnabled.Consequence Without Action
Additional GC threads may be used by the low pause collector during concurrent marking.Recommended Fix
If this behavior is not desired, turn off this feature with the command line flagCMSConcurrentMTEnabled.Further Reading
3.2.3 Monitoring and Management
jstack, jmap and jinfo work on Windows
Description
A subset of thejstack,jmap, andjinfofunctionalities now work on Windows in addition to Linux and Solaris. They are:
jstack [-l] <pid>jmap -histo or -dump <pid>jinfo -flag <pid>Further Reading
- http://java.sun.com/javase/6/docs/technotes/tools/share/jstack.html
- http://java.sun.com/javase/6/docs/technotes/tools/share/jmap.html
- http://java.sun.com/javase/6/docs/technotes/tools/share/jinfo.html
- http://java.sun.com/developer/technicalArticles/J2SE/monitoring/
- http://java.sun.com/javase/6/webnotes/trouble/
New jstack -l and -F options
Description
Newjstackoptions are:
-l
long listing. Print additional information about locks.-F
to force a thread dump. Use whenjstack [-l] <pid>does not respond (process is hung)Further Reading
- http://java.sun.com/javase/6/docs/technotes/tools/share/jstack.html
- http://java.sun.com/developer/technicalArticles/J2SE/monitoring/
- http://java.sun.com/javase/6/webnotes/trouble/
New jmap -histo, -dump, -finalizerinfo and -F options
Description
New jmap options are:
-histo[:live]
to print histogram of java object heap; if thelivesuboption is specified, only count live objects-finalizerinfo
to print information on objects awaiting finalization-dump
to dump java heap in hprof binary format-F
to force. Use with-dump:<dump-options> <pid>or-histoto force a heap dump or histogram when<pid>does not respond. Thelivesuboption is not supported in this mode.Further Reading
- http://java.sun.com/javase/6/docs/technotes/tools/share/jmap.html
- http://java.sun.com/developer/technicalArticles/J2SE/monitoring/
- http://java.sun.com/javase/6/webnotes/trouble/
New jinfo -flag option
Description
Newjinfooptions are:
-flag <name>
to print the value of the named VM flag-flag [+|-]<name>
to enable or disable the named VM flag-flag <name>=<value>
to set the named VM flag to the given valueFurther Reading
- http://java.sun.com/javase/6/docs/technotes/tools/share/jinfo.html
- http://java.sun.com/developer/technicalArticles/J2SE/monitoring/
- http://java.sun.com/javase/6/webnotes/trouble/
New jhat tool - Heap Analysis Tool
Description
HAT has been a very useful heap analysis tool and we include it in JDK 6 as an experimental tool.Further Reading
- CR 5102009
- http://java.sun.com/javase/6/docs/technotes/tools/share/jhat.html
- http://java.sun.com/developer/technicalArticles/J2SE/monitoring/
- http://java.sun.com/javase/6/webnotes/trouble/
New JConsole -pluginpath option
Description
Provide ajconsoleplug in interface for user to define custom tabs.Further Reading
- CR 6179281
- http://java.sun.com/javase/6/docs/jdk/api/jconsole/spec/index.html
JTopDemo under the<JDK6>/demo/management/JTopdirectory- Scripting console demo under the
<JDK6>/demo/scripting/jconsole-plugindirectory
3.2.4 Java Compiler
The compiler, javac, has new command line options for annotation processing:
-A
Pass options to annotation processors-proc
Controls whether annotation processing and/or compilation is done-processor
Names of the annotation processors to run-processorpath
Specify where to find annotation processors-s
Specify the directory where to place generated source files-Xprefer
Specify which file to read when both a source file and class file are found for a type-Xprint
Print out textual representation of specified types for debugging purposes-XprintProcessorInfo
Print information about which annotations a processor is asked to process.-XprintRounds
Print information about initial and subsequent annotation processing rounds.Other options that were added in JDK 6 include:
-implicit
Controls the generation of class files for implicitly loaded source files-fullversion-source 6
Specifies the version of source code accepted-target 6
Generate class files that target a specified version of the VMThe only difference between
-source 6and-source 5is that encoding errors become fatal. Starting in JDK 5, the compiler would warn about such problems.Further Reading
All the options are documented at http://java.sun.com/javase/6/docs/technotes/tools/windows/javac.html#options
3.2.5 Core Libraries
New JAR tool flag for creating executable JAR files
Description
An application can be packaged into an executable jar file. Such a jar file's MANIFEST has a Main-Class entry. Prior to JDK 6, this would be set by a manually placing that entry in the MANIFEST. In JDK 6, thejarcommand can provide the entry, if the-eoption is given on the command line along with an entry point which specifies the name of the class file.Consequence Without Action
This new flag does not have any impact on the existing jar command usage. It is only when both-m("use the provided manifest file") and-e("set the entry point to be that given on the command line") options both specified and the provided manifest file already contains a Main-Class entry, that the jar command results in an ambiguousMain.classspecification, leading to an error and the jar creation or update operation is aborted.Recommended Fix
The new flag-eis for setting the entry point. When using this new flag, ensure that a manifest specified-mflag does not contain a Main-Class entry.Further Reading
File.isFile() now return "false" for reserved device names on Windows platform
Description
java.io.File.isFile()previously returnedtrueif the file denoted by theFileobject is a device (which means the file name of thisFileobject is or includes the Windows reserved device names, such as CON, PRN, AUX, NUL, COM1, COM2 LPT1, LPT2...) on Windows platform. It always returnsfalseon Solaris and Linux for special device files. The spec ofFile.isFile()does not explicitly specify whether it should returntrueorfalsefor special device files, instead it allowsisFile()to return based on system-dependent criteria. From JDK 6,java.io.File.isFile()always returnsfalsefor device names on Windows, which is indeed an incompatible change but worthing doing.Consequence Without Action
File.isFile()no longer returnstruefor device names on Windows platforms.Recommended Fix
The existing code should be updated accordingly if its logic assumesFile.isFile()returnstruefor device name on Windows platform.Further Reading
3.3 New Developer Tools that Replace Old Ones
3.3.1 Monitoring and Management
jstack can be used to replace control-break or SIGQUIT thread dump support
Description
jstacknow works on all platform to obtain thread dump and detect deadlock on a given VM.Recommended Fix
Usejstackinstead of control-break orSIGQUITFurther Reading
- http://java.sun.com/javase/6/docs/technotes/tools/share/jstack.html
- http://java.sun.com/developer/technicalArticles/J2SE/monitoring/
- http://java.sun.com/javase/6/webnotes/trouble/
jmap -histo can be used to replace control-\ or SIGQUIT heap histogram support with VM -XX:+PrintClassHistogram option
Description
jmap -histoworks on all platforms to obtain a heap histogram.Recommended Fix
Usejmapinstead of control-break orSIGQUITFurther Reading
- http://java.sun.com/javase/6/docs/technotes/tools/share/jmap.html
- http://java.sun.com/developer/technicalArticles/J2SE/monitoring/
- http://java.sun.com/javase/6/webnotes/trouble/
jmap -dump or jconsole to obtain a heap dump
Description
jmap -dumpworks on all platforms to obtain a heap dump at runtime. Also jconsole enables to invoke thecom.sun.management.HotSpotDiagnosticMXBeanAPI at runtime.Recommended Fix
Usejmaporjconsoleto get a heap dump.Further Reading
- http://java.sun.com/javase/6/docs/technotes/tools/share/jconsole.html
- http://java.sun.com/javase/6/docs/technotes/tools/share/jhat.html
- http://java.sun.com/javase/6/docs/technotes/tools/share/jmap.html
- http://java.sun.com/developer/technicalArticles/J2SE/monitoring/
- http://java.sun.com/javase/6/webnotes/trouble/
3.3.2 Annotation Processing
Description
javacprovides direct support for annotation processing, superseding the need for the separate annotation processing tool,apt.The API for annotation processors is defined in the
javax.annotation.processingandjavax.lang.modelpackages and subpackages.Further Reading
3.4 Changed Developer Tool Defaults/Behaviors
3.4.1 JDI and JDWP
jdb:
Supports the new
ProcessAttachconnector:
Connector:com.sun.jdi.ProcessAttachTransport: local
description: Attaches to debuggee by process-id (pid)Required Argument:
pid(no default)
description:pidArgument:
timeout(no default)
description: Timeout while waiting to attachA change to the trace command
Instead of
trace methods [thread]-- trace method entry and exitWe have
trace [go] methods [thread]
- trace method entries and exits.
- All threads are suspended unless
gois specified
trace [go] method exit | exits [thread]
- trace the current method's exit, or all methods' exits
- All threads are suspended unless
gois specified3.4.2 Annotation Processing
Description
javacprovides direct support for annotation processing, superseding the need for the separate annotation processing tool,apt.The API for annotation processors is defined in the
javax.annotation.processingandjavax.lang.modelpackages and subpackages.Further Reading
3.5 Newly Supported Platform Behaviors
3.5.1 Swing
Swing's GTK and Windows Look and Feel now take advantage of the native system to do much of the rendering. As a result, the visual appearance of components better match their native counterpart, and are themeable to the same extent (and by the same mechanism) as the native system. Swing components are also Vista ready.
3.6 Other
3.6.1 Networking
Fix for problem with lookups of localhost with JNDI-DNS provider
Description
This change resolves a problem where it was expected that the name service being accessed by JNDI must have an explicit entry forlocalhostin order forInetAddress.getLocalHost()to succeed. This change removes the restriction. If a name service no longer includes alocalhostentry, an error will not be returned.Further Reading
Change default DNS caching behavior for code not running under security manager
Description
Previously, DNS lookups were cached in the VM forever by default. This change maintains this behavior for code running under a security manager (for security reasons). However, for code not using a security manager, the restriction has been relaxed so that updates to DNS can be detected by the default configuration. Applications that wish to keep the old behavior can edit thenetworkaddress.cache.ttlsecurity property.Further Reading
HTTP Keep-Alive improvements
Description
This enhancement provides the ability to reuse connections where not all of the response body has been read by user code. Previously in this case, even when keep-alive was enabled (as it is by default), the connection had to be closed because of the residual data on the socket.We have implemented an asynchronous cleanup of unread response body from the underlying socket. If the
InputStreamis closed before all of the response body is read, its underlying TCP connection is put on a queue so that the remaining data can be read and the connection put into the keep-alive cache. The queue is serviced on demand by a new thread,Keep-Alive-SocketCleaner.Depending on the application requirements and your network speed, you may want to tune this feature. This is available through the network properties
http.KeepAlive.remainingDataandhttp.KeepAlive.queuedConnectionsin../jre/lib/net.properties .There are two HTTP Keep-Alive settings.
remainingDatais the maximum amount of data in kilobytes that will be cleaned off the underlying socket so that it can be reused (default value is 512K)queuedConnectionsis the maximum number of Keep-Alive connections to be on the queue for clean up (default value is 10).
http.KeepAlive.remainingData=512
http.KeepAlive.queuedCon nections=10We have taken 512K as the default value for the maximum amount of data remaining to be read. That is, if there is 512K or less of unread response body on the
InputStreamthen it will be queued for async cleanup, otherwise the underlying socket will be closed. This value was chosen as an approximate cost of creating a new connection but may vary depending on the connection type. For example, HTTPS connections can take some time to perform the SSL handshake.
http.KeepAlive.queuedConnectionsis simply to ensure that the queue does not grow out of proportion. If you are planning to make use of this feature in your code (or are using third party code), you may want to increase this default value.Further Reading
3.6.2 Deployment
Deploy Cache Changes
Description
The location and format of the deploy cache has changed. We have never documented the format and location, but it may have been reverse-engineered.Consequence Without Action
A program that assumes the old format and location will not work in JDK 6.Recommended Fix
Do not make assumptions about the location or format of the cache. These are implementation details that can change.Further Reading
JNLPClassLoader
Description
JNLPClassLoaderis not a subclass ofURLClassLoaderin J2SE 1.5, but is in JDK 6. In J2SE 1.5,JNLPClassLoadercould return a file URL (pointing to the local cache) but in JDK 6 this could not happen. In JDK 6,JNLPClassLoaderwill always return the Web URL of the resource.Consequence Without Action
A program that expected a file URL could fail in JDK 6.Recommended Fix
Do not make assumptions about the format or type of the returned URL as these are not part of the documented or public interface. The previous behavior was wrong, and we have corrected it.Further Reading
This section is useful for developers of tools that support application development on JDK 6. It is aimed at advanced developers who are creating third party tools that build on the features of J2SE 1.5, and who wish to ensure their tools continue to work in conjuction with JDK 6.
4.1 Class File Format Changes
4.1.1 JSR 202 Classfile Changes
Description
New specification:
http://java.sun.com/docs/books/vmspec/2nd-edition/jvms-proposed-changes.htmlJSR 202: http://jcp.org/en/jsr/detail?id=924
Third party tool vendors need to know that the JDK
.jarfiles still ship with classfile format 49.Further reading
Deployment impact
The compatibility of Pack200 should be addressed in the Deployment Guide (http://java.sun.com/j2se/1.5.0/docs/guide/deployment/deployment-guide/pack200.html) as that is most useful to deployers of Java, however in this context a brief description or a pointer to the Deployment guide should suffice.Background information extracted from our 6.0 SRT slides
Updates to VM Specification:
- New class file version: 50.0
- New attribute of Code:
StackMapTable- New type checking verifier
- No more
jsrinstructions.- In JDK 6,
javacby default generates version 50.0 class files with aStackMapTableattribute. It can generate older version class files by explicitly specifying the target options.Adopted (with modifications) from CLDC:
javacencodes type information inStackMapTable.- Type checking verifier uses these type information to generate a proof of type safety in one pass over the bytecodes.
- Type checking verifier is only used to verify class files with version 50.0. Older class files are still verified by the traditional verifier.
- Traditional verifier can be forced with the
-XX:-UseSplitVerifierflag.Missing or incorrect
StackMapTableattributes for version 50.0 class files can result inVerifyErrorexceptions. Tools that rewrite bytecode in version 50.0 class files and do not correctly update theStackMapTablemay fail to verify and trigger exceptions. For errors that could be caused by this, the VM will automatically failover and use the old verifier unless the-XX:-FailOverToOldVeriferflag is present.Because of failover, verification errors found by the type checker may not be seen if the errors are not found by the old verifier. While possible, this should be very rare. The new verifier implementation is more lazy about loading referenced classes than the old verifier. This may result in classes being loaded later or not at all. It is not trivial to predict if the verifier will need to load a referenced class.
A number of bugs fixed in JDK 6 deal with specification conformance.
Most of these fixes are tied to the class file version to maintain compatibility with older, possibly non-conformant class files. Occasionally, we have a flag to revert to old behavior (as noted).
- CR 4012001
ACC_Abstractrequired for interfaces when version >= 50.0- CR 4293149, 6383849 Stop relaxed access checking for classes in the same package with local class loader when version >= 49.0
- CR 5060487
-XX:+RelaxAccessControlChecksreverts to old behavior Only allow call of protected constructor by instances of a subclass (6.0 & 5.0_09 & 1.4.2_12)- CR 6324107 Disallow method with no code attribute
- CR 6339875 Disallow definition of classes in the
java.*packages. Already enforced byClass.defineClass()calls which take a name. Closed the hole forJNI_DefineClass()and theClass.defineClass()with no name argument.- CR 5031222 Removed
JDK1_1InitArgsstruct fromjni.h. Continue to useJavaVMInitArgs.
4.1.2 Java Compiler
Descripion
The class file format was updated in JDK 6. The changes includes improvements to the verification scheme. Generally, this should speed up verification. By default,javacwill generate class files in the new format, that is,-target 6is the default. Use-target 5or lower if targetting an older JVM.4.2.Deprecation of any Tool-specific or com.sun.* APIs
The class
com.sun.tools.javac.Mainis no longer the preferred way to invokejavacfrom a program. Instead the features injavax.toolsshould be used.Furthermore, the compiler will emit warnings if unsupported Sun proprietary API is used. This will help developers realize if they are depending on undocumented API that may change without notice.
|
Copyright © 2007 Sun Microsystems, Inc. All Rights Reserved. |
|