Thursday, August 16, 2012

JDK7: Part 2 - Java 7, The "Dolphin" new features & enhancements.

Java 7 was released in July of 2011 and introduced a number of new features. In the Java SDK documentation, you may see it referred to as Java 1.7, it streamline the development process and has a great and improved enhancements in many areas specially IO and concurrent processing.

In this article I will address a variety of topics involved in JDK 7 as new features and enhancements on two parts.

Part 1 introduces the core language and JVM enhancements, IO operations from using paths for locating, managing the files & directories and getting there information. Also I will introduce the managing of the files Systems and finally streaming of new IO2.

While this part covers the remaining topics including GUI enhancements and its event handling, Database, security and system enhancements. And finally the great enhancement and huge improvement had done in the threading and concurrency API.


Table of contents:

1.       Language Improvements.

2.       Using Paths to Locate Files and Directories.

3.       Obtaining File and Directory Information.

4.       Files and Directories Management.

5.       Managing Filesystems.

6.       Stream IO in Java 7.

7.       Graphical User Interface (GUI) Improvements.

8.       GUI events handling.

9.       Database, Security, and System Enhancements.

10.   Threading & concurrent processing.

11.   References.


7.      Graphical User Interface (GUI) Improvements.


The ability to develop applications that have a Graphical User Interface (GUI) interface has been enhanced in Java 7. Some of these are minor improvements and others are major, such as using the javax.swing.JLayer decorator class.


It is now possible to mix heavyweight and lightweight components in an application without adding special code to make it work as desired. This improvement is largely transparent to users of Java 7.


To ease the development of applications, three basic window types have been introduced. These should simplify the creation of certain types of applications. The JFrame class supports a setType() method, which configures the general appearance of a window to one of the three types. This can simplify the setting of a window's appearance.


To set the window type, use the setType() method with one of the three window types, as found in the java.awt.Window class:


         Type.NORMAL: This represents a normal window and is the default value for windows.


         Type.POPUP: This is a temporary window intended to be used for small areas, such as tool tips.


         Type.UTILITY: This is also a small window for objects, such as a palette.


The overall appearance of an application may include such characteristics as its opacity and shape. You can manage and control a window's opacity and creating a varying gradient translucent window. Controlling the shape of a window, such as making it round or some irregular shape, is also controllable.


The translucency-related capabilities were added originally as part of the Java 6 Update 10 release. However, they were implemented as part of the private com.sun.awt.AWTUtilities class. This capability has been moved to the java.awt package. Javax.swing.JComponents has borders whose appearance can be controlled. In Java 7, several new borders have been added.


Improvements have also been made in the use of the file dialog and print dialog boxes. These enhancements are the Handling multiple file selection in the FileDialog class and Controlling the print dialog box type.


The ability to draw over a JComponent has been added. This allows the use of special effects, which were not easily achieved in earlier versions of Java. You can use the new JLayer decorator for a password field and also create a watermark for windows.


The following is the code used to develop a minimal window-based application. An ApplicationRunner class is used to start and display the JFrame-derived ApplicationWindow class. The ApplicationRunner class is shown as follows:



The invokeLater method uses an inner class to create and then display the ApplicationWindow. This window is set up in its constructor. It is a simple window that has an Exit button, which we will use to close the application and you can enhance and customize it to suite your application :


When this code is executed, the output should appear as shown in the following screenshot:



There are a number of minor improvements introduced in Java 7. For example, the protected static java.awt.Cursor array has been deprecated. Instead, use the getPredefinedCursor method. This method takes an integer argument and returns a Cursor object.


A new HSV tab was introduced to the java.swing.JColorChooser dialog box. It appears as shown in the following screenshot:



Also in Java 7, it is possible to customize a dragged JApplet's title and to specify whether it should be decorated or not. This is accomplished from a script tag as follows:


<script src="http://javascript source file"></script>
<script>
    var attributes = { code:'AppletName', width:100, height:100 };
    var parameters = {jnlp_href: 'appletname.jnlp',java_decorated_frame: 'true', java_applet_title: 'A Custom Title'};
    deployJava.runApplet(attributes, parameters, '7'7);
</script>

The java_decorated_frame parameter is set to true to specify that the window should be decorated. The title of the window is specified using the java_applet_title parameter. This example is adapted from http://download.oracle.com/javase/tutorial/deployment/applet/draggableApplet.html. More details on how to create draggable applets can be found at that site.


A couple of miscellaneous changes need to be noted. The Nimbus Look and Feel has been moved from the com.sun.java.swing package to the javax.swing package. The isValidateRoot method has been added to the Applet class to indicate that the container is a valid root. Lastly, a new Java2D graphics pipeline based upon the X11 XRender extension has been added to provide better access to Graphical Processing Units (GPU).


8.      GUI events handling.


There have been several additions to Java 7 that address events or are related to events. This includes the handling of mouse events where enhanced support is provided for the detection of mouse buttons and for using high resolution mouse wheels.


When a window is made visible with either the setVisible or toFront methods, we now have the ability to control whether they should gain focus or not. Some windows may be displayed for informational or status purposes and do not necessarily need or warrant focus.


You should be familiar with the behavior of modal dialog boxes. Essentially, the modal dialog box will not return focus to the main window until it is closed. There are times when it is desirable to mimic this behavior without using a dialog box. For example, the selection of a button that performs a relatively long running calculation may benefit from this behavior.


While not common, spurious interrupts can occur when using the wait method. The java.awt.event.InvocationEvent class' isDispatched method can be used to handle spurious interrupts.


Applets have also been enhanced with regards to their ability to communicate with JavaScript code. So JavaScript code can be made aware of and take advantage of knowing when an applet loads.


Other minor event-related improvements in Java 7 are the availability of accessing extended key codes and the implementation of the java.awt.iamg.ImageObserver interface for the JSlider class.


The KeyEvent class has been augmented with two new methods: getExtendedKeyCode and getExtendedKeyCodeForChar. The first method returns a unique integer for a key, but unlike the getKeyCode method, its value depends on how the keyboard is currently configured. The second method returns the extended key code for a given Unicode character.


The imageUpdate method has been added to the JSlider class. This permits the class to monitor the status of an image being loaded, though this capability is probably best used with classes that are derived from JSlider.


9.      Database, Security, and System Enhancements.


This topic covers database, security, and system type enhancements that have been made to Java 7.


Some of these enhancements are minor and will be addressed in this article. Others are more significant and will be detailed in other articles. Due to the rather specialized nature of some topics, such as those typified by some of the security enhancements, they will be mentioned but not explained here.


Java Database Connectivity JDBC 4.1:


Multiple enhancements have been made to JDBC in Java 7, which now supports JDBC 4.1.


Note: Some of the improvements depend on third party driver support not available in early driver versions. When this happens, you may receive an AbstractMethodException. When testing the database, ensure that you are working with a driver that supports the JDBC 4.1 functionality.


Drivers can be found at http://developers.sun.com/product/jdbc/drivers.


The Using the RowSetFactory recipe deals with the use of the javax.sql.rowset.RowSetFactory interface and the javax.sql.rowset.RowSetProvider class, which permits the creation of any row sets as supported by a given JDBC driver.


There are a number of other improvements in database's support included in Java 7, and include such issues as determining the name of the current schema and providing access to hidden columns.


In addition to these database enhancements, the try-with-resource statement can be used with any object that implements the java.sql package's Connection, ResultSet, or Statement interfaces.


This language improvement simplifies the process of opening and closing resources. The general use of the try-with-resource statement is to improve exception handling.


The Statement interface has been enhanced with two new methods. The first method, closeOnCompletion, is executed to specify that the Statement object will be closed when result sets that use the connection are closed. The second method, isCloseOnCompletion, returns a Boolean value indicating whether the statement will be closed when this criteria is met.


Networking:


Network enhancements to Java 7 include the addition of two methods to the java.net.URLClassLoader class:

         close: This method will close the current URLClassLoader, so that it is no longer able to load classes or resources. This addresses a problem found on Windows, as detailed at http://download.oracle.com/javase/7/docs/technotes/guides/net/ClassLoader.html


         getResourceAsStream: This method returns an InputStream for the resource specified by its String argument


Assistance is also provided to support stream connections using the InfiniBand (IB). This technology uses Remote Direct Memory Access (RDMA) to move data directly between the memories of different computers. This support is provided through the Sockets Direct Protocol (SDP) network protocol. The specialized nature of this technology precludes further discussion.


the improvements also made in the support of MXBeans. This includes different methods for accessing these management type beans.


Language libraries:


The java.lang.ProcessBuilder class has improved redirect capabilities as introduced by the ProcessBuilder.Redirect class. Which is the Redirecting input and output from operating systems processes.


Java 7 has also improved the way applets can be embedded in an HTML page.


Security:


The Java Secure Socket Extension (JSSE) is used to secure Internet communications using Secure Sockets Layer (SSL) and Transport Layer Security (TLS). JSSE assists in data encryption, authentication, and maintaining message integrity. In Java 7, several enhancements have occurred.


Security enhancements include the incorporation of Elliptic Curve Cryptography (ECC) algorithms. This class of encryption algorithms is more resistant to brute force attacks. A portable implementation of the algorithm has been provided. New exception classes have been added or enhanced to enhance security.


The new java.security.cert.CertificateRevokedException, when thrown, means that an X.509 certificate has been revoked. The java.security.cert.CertPathValidatorException class has been enhanced with the addition of a new constructor that takes a CertPathValidatorException.Reason object. This object implements the CertPathValidatorException.BasicReason enumeration that enumerates the reason for the exception. The CertPathValidatorException class's getReason method returns a CertPathValidatorException.Reason object.


Java 7 also supports TLS 1.1 and 1.2 specifications and improves upon this support. The Sun JSSE provider supports TLS 1.1 and TLS 1.2 as defined in RFC 4346 (http://tools.ietf.org/html/rfc4346) and RFC 5246 (http://tools.ietf.org/html/rfc5246) respectively. These include support to protect against cipher block chaining attacks and new cryptographic algorithms.


In addition, there are a few other TKS-related enhancements:

 


         The SSLv2Hello protocol has been removed from the list of protocols that are enabled by default.


         A flaw relating to TLS renegotiation has been fixed in Java 7. Details regarding this flaw can be found at http://www.oracle.com/technetwork/java/javase/documentation/tlsreadme2-176330.html.


         During TLS 1.1/1.2 handshaking, Java 7 has improved the process of version number checking.


Weak cryptographic algorithms can be disabled using the jdk.certpath.disabledAlgorithms property for the Sun provider. By default, the MD2 algorithm is disabled. This property is specified in the jre/lib/security/java.security file.


The default setting is shown as follows:


jdk.certpath.disabledAlgorithms=MD2

 


It is also possible to specify not only the algorithm, but restrictions on the key size.

Algorithm restrictions can also be placed at the TLS level. This is accomplished using the jdk.tls.disabledAlgorithms security property in the jre/lib/security/java.security file. Anexample is as follows:


jdk.tls.disabledAlgorithms=MD5, SHA1, RSA keySize < 2048

Currently, this property is specific to the Oracle JSSE implementation and may not be recognized by other implementations.


The Server Name Indication (SNI) JSSE extension (RFC 4366) enables TLS clients to connect to virtual servers, that is, multiple servers with different network names that use the same supporting network address. This is enabled to true by default, but can be set to false for systems where the extension is not supported.


The jsse.enableSNIExtension system property is used to control this setting. It can be set using the –D java command option shown as follows:


java –D jsse.enableSNIExtension=true ApplicationName


It is also possible to set this property using the setProperty method shown as follows: System.setProperty("jsse.enableSNIExtension","true");


Note that the property name may change in the future.


10.      Threading & concurrent processing.


Support for concurrent applications has been improved in Java 7. Several new classes have been introduced that support the parallel execution of tasks. The ForkJoinPool class is used for applications, which use the divide-and-conquer technique to solve a problem. Each sub problem is forked (split) as a separate thread and later joined, if necessary to provide a solution. The threads used by this class are normally subclasses of the java.util.concurrent.ForkJoinTask class and are lightweight threads.


In addition, the java.util.concurrent.Phaser class has been introduced to support the execution of a collection of threads in a series of phases. A group of threads are synchronized, so that they all execute and then wait for the completion of the others. Once they have all completed, they can be re-executed for a second phase or subsequent phase.


Two new classes designed to work safely with multiple threads The java.util.concurrent.ConcurrentLinkedDeque class safely with multiple threads and the java.util.concurrent.LinkedTransferQueue class, examples of their use in support of the producer/consumer framework.


The java.util.concurrent.ThreadLocalRandom class is new and provides better support for random number generation used between multiple threads.


Two new constructors have been added to the java.util.ConcurrentModificationException class. They both accept a Throwable object used to specify the cause of the exception. One of the constructors also accepts a string that provides a detail message regarding the exception.


Java 7 has improved the use of class loaders by modifying the locking mechanism to avoid deadlocks. In multi-threaded custom class loaders prior to Java 7, certain custom class loaders were prone to deadlocks, when they used a cyclic delegation model.


Consider the following scenario. Thread1 tries to use a ClassLoader1 (locking ClassLoader1) to load class1. It then delegates the loading of class2 to ClassLoader2. At the same time, Thread2 uses ClassLoader2 (locking ClassLoader2) to load class3, and then delegates the loading of class4 to ClassLoader1. Since both class loaders are locked and both the threads need both loaders, a deadlock situation occurs.


The desired behavior of a concurrent class loader is to load different classes from the same instance of the class loader concurrently. This requires locking at a finer level of granularity, such as locking a class loader by the name of the class being loaded.


Synchronization should not be done at the class loader level. Instead, a lock should be made on a class level, where the class loader allows only a single instance of the class to be loaded at a time by that class loader.


Some class loaders are capable of loading classes concurrently. This type of class loader is called parallel capable class loaders. They are required to register themselves during their initialization process using the registerAsParallelCapable method.


If the custom class loader uses an acyclic hierarchal delegation model, no changes are needed in Java. In a hierarchal delegation model, delegation is first made to its parent class loader. Class loaders that do not use the hierarchical delegation model should be constructed as parallel capable class loaders in Java.


To avoid deadlock for custom class loaders:


         Use the registerAsParallelCapable method in the class initialization sequence. This indicates that all instances of the class loader are multi-thread safe.


         Make sure that the class loader code is multi-thread safe. This involves:


§ Using an internal locking scheme, such as the class name locking scheme used by java.lang.ClassLoader.


§ Removing any synchronization on the class loader lock.


§ Ensuring that critical sections are multi-thread safe.


         It is recommended that the class loader overrides the findClass(String) method.


         If the defineClass methods are overridden, then ensure that they are only called once per class name.


More detail about this problem can be found at http://openjdk.java.net/groups/core-libs/ClassLoaderProposal.html.


11.      References.


1. http://docs.oracle.com/javase/tutorial/index.html.


2. Java SE Technical Documentation http://docs.oracle.com/javase/index.html.


3. Description of Java Conceptual Diagram http://docs.oracle.com/javase/7/docs/technotes/guides/desc_jdk_structure.html.


4. The Java Tutorial http://docs.oracle.com/javase/tutorial/index.html.


5. http://tamanmohamed.blogspot.com/2012/03/jdk7-part-1-power-of-java-7-nio2-jsr.html


6. Java 7 Cookbook book.


7. Java 7 Recipes A Problem-Solution Approach book.


8. Beginning Java 7 book.


9. The Java™ Language Specification (JLS) Java SE 7 Edition.


10. The Java Virtual Machine Specification Java SE 7 Edition.


Finally thanks for reading, for full article check Part 1.