Вы находитесь на странице: 1из 7

Java 7 Changes, Features and Enhancements

May 28, 2014 by Lokesh Gupta

I have already covered many java 7 changes which were new in the release. In this post, I am
creating a summary of them so that if anyone interested can take a quick look into all features in
short time.

Features covered in this post

Improved type Inference Or Diamond Operator


Automatic resource management with try-with-resources
NIO 2.0
Exception handling improvements
Suppressed exceptions
Catch Multiple Exceptions in catch block
Number formatting enhancement
String class support in switch statement
Binary Literals with prefix "0b"
ForkJoin Framework
Automatic reloading with WatchService
G1 Garbage Collector

Improved type Inference


Before java 7, while using generics you had to supply type parameters to variables types and to
their actual types. Now, it has been relieved a bit in this new java 7 feature, and a blank diamond
on right side of declaration will work fine.

Compiler is smart enough in java 7 to identify that blank diamond infer to type defined on left
hand side of declaration.

public class ElvisOperatorTest {


public static void main(String[] args) {
@SuppressWarnings("unused")
Map params = new HashMap<>();
}
}

Automatic resource management with try-with-resources


Before java 7, we had to use finally blocks to cleanup the resources. Finally blocks were not
mandatory, but resource clean up was to prevent the system from being corrupt. With java 7,
there is no need to explicit resource cleanup. Its done automatically. Automatic resource cleanup
is done when initializing resource in try-with-resources block (try(…) {…}).
Cleanup happens because of new interface AutoCloseable. Its close method is invoked by JVM
as soon as try block finishes. You are not supposed to call close() method in your code. This
should be called automatically bu JVM. Calling it manually may cause unexpected results.

public class ResourceManagementInJava7


{
public static void main(String[] args)
{
try (BufferedReader br = new BufferedReader(new
FileReader("C:/temp/test.txt")))
{
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null)
{
System.out.println(sCurrentLine);
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}

NIO 2.0
Java SE 7 introduced java.nio.file package and its related package,
java.nio.file.attribute, provide comprehensive support for file I/O and for accessing the
default file system. Path class has been a big addition which allow you to represent any path in
operating system in uniform way. New APIs complements older one and provides several useful
method checking, deleting, copying, and moving files. You can also create symbolic links and
hard links like in linux. JDK 7 new file API is also capable of searching for files using wild
cards/regex. You also get support to watch a directory for changes.

Go ahead and explore all these changes in linked webpages.

Exception handling improvements


Java 7 has brought some nice enhancements in exception handling as well. These can be broadly
divided into two features:

Suppressed exceptions
Suppressed exceptions, as name suggest, are exceptions thrown in the code but were ignored
somehow. If you remember try-catch-finally block execution sequence and how they return any
value or exceptions, you will recall that exceptions thrown in finally block are suppressed is
exception is thrown in try block also. Before java 7, you was informed about these exceptions by
logging if implemented, but you didn’t have any control over these types of exceptions once
finally block is over. With new features in java 7 you got control over these suppressed
exceptions as well.

A example usage is below:

public class SuppressedExceptionDemoWithTryFinallyNew


{
/**
* Executable member function demonstrating suppressed exceptions
* Suppressed expression is added back in primary exception
*/
public static void memberFunction() throws Exception
{
Throwable th = null;
DirtyResource resource= new DirtyResource();
try
{
resource.accessResource();
}
catch(Exception e)
{
th = e;
throw e;
}
finally
{
try
{
resource.close();
}
catch(Exception e)
{
if(th != null)
{
e.addSuppressed(th); //Add to primary exception
throw e;
}
}
}
}
/**
* Executable function demonstrating suppressed exceptions.
*/
public static void main(String[] arguments) throws Exception
{
try
{
memberFunction();
}
catch(Exception ex)
{
err.println("Exception encountered: " + ex.toString());
final Throwable[] suppressedExceptions = ex.getSuppressed();
final int numSuppressed = suppressedExceptions.length;
if (numSuppressed > 0)
{
err.println("tThere are " + numSuppressed + "
suppressed exceptions:");
for (final Throwable exception : suppressedExceptions)
{
err.println("tt" + exception.toString());
}
}
}
}
}

Output:

Exception encountered: java.lang.NullPointerException: Remember me. I am your


worst nightmare !! I am Null pointer exception !!
There are 1 suppressed exceptions:
java.lang.RuntimeException: I wanted to access this resource. Bad
luck. Its dirty resource !!!

Read more on linked article.

Catch Multiple Exceptions in catch block


In this feature, now you can catch multiple exceptions in single catch block. Before java 7, you
was restricted to catch only one. To specify the list of expected exceptions a pipe (‘|’) character
is used.

Lets understand using an example.

try
{
//Do some processing which throws NullPointerException; I am sending
directly
throw new NullPointerException();
}

//You can catch multiple exception added after 'pipe' character


catch(NullPointerException | IndexOutOfBoundsException ex)
{
throw ex;
}
Remember: If a catch block handles more than one exception type, then the catch parameter is
implicitly final. In this example, the catch parameter ex is final and therefore you cannot assign
any values to it within the catch block.

Number formatting enhancement


If you have to read a number “1000000“, then how much convenient it read in first site. Not
much, right?? We have a habit of reading numbers in 10,00,000 format. Good news is that java
has started supporting to write numbers in this format. Well, not exactly this but a matching
format.

Now you can write above number like this : 10_00_000. Good enough, Isn’t it??

/**
* Supported in int
* */
int improvedInt = 10_00_000;
/**
* Supported in float
* */
float improvedFloat = 10_00_000f;
/**
* Supported in long
* */
float improvedLong = 10_00_000l;
/**
* Supported in double
* */
float improvedDouble = 10_00_000;

String class support in switch statement


If you remember the switch statement before java 7, it supported only int and enum types. Now
with java 7 release, support for String class has also been added. Lets see using an example.

switch (token)
{
case ("one"):
return "Token one identified";

case ("two"):
return "Token one identified";

case ("three"):
return "Token one identified";

case ("four"):
return "Token one identified";

default:
return "No token was identified";
}

Binary Literals with prefix “0b”


In JDK 7, you can express literal values in binary with prefix ‘0b’ (or ‘0B’) for integral types
(byte, short, int and long). Before JDK 7, you can only use octal values (with prefix ‘0’) or
hexadecimal values (with prefix ‘0x’ or ‘0X’). e.g.
int sameVarOne = 0b01010000101;

or if use the number formatting feature as well.

int sameVarTwo = 0B01_010_000_101;

ForkJoin Framework
The effective use of parallel cores in a Java program has always been a challenge. There were
few home-grown frameworks that would distribute the work across multiple cores and then join
them to return the result set. Java 7 has incorporated this feature as a Fork and Join framework.

Basically the Fork-Join breaks the task at hand into mini-tasks until the mini-task is simple
enough that it can be solved without further breakups. It’s like a divide-and-conquer algorithm.
One important concept to note in this framework is that ideally no worker thread is idle. They
implement a work-stealing algorithm in that idle workers steal the work from those workers who
are busy.

It’s based on the work of Doug Lea, a thought leader on Java concurrency. Fork/Join deals with
the threading hassles; you just indicate to the framework which portions of the work can be
broken apart and handled recursively. It employs pseudo-code (as taken from Doug Lea’s paper
on the subject):

Result solve(Problem problem) {


if (problem is small)
directly solve problem
else {
split problem into independent parts
fork new subtasks to solve each part
join all subtasks
compose result from subresults
}
}

Automatic reloading with WatchService


Every application has some configuration which is expected to be refreshed on every change in
configuration file. Past approaches to solve this problem had consisted of having a Thread, which
periodically poll for file change based on ‘last update time stamp’ of configuration file.

Now with java 7, things have changed. Java 7 has introduced an excellent feature:
WatchService. A WatchService is JDKs internal service which watches for changes on
registered objects. These registered objects are necessarily the instances of Watchable interface.
When registering the watchable instance with WatchService, we need to specify the kind of
change events we are interested in.

A example usage of WatchService is given in linked article.


G1 Garbage Collector
JDK 7 introduced a new Garbage Collector known as G1 Garbage Collection, which is short
form of garbage first. G1 garbage collector performs clean-up where there is most garbage. To
achieve this it split Java heap memory into multiple regions as opposed to 3 regions in the prior
to Java 7 version (new, old and perm-gen space). G1 is quite predictable and provides greater
through put for memory intensive applications.

Вам также может понравиться