|
|
|||||
A look at Java 7's new featuresA survey of important updates and changes in Java 7.There are a number of features in Java 7 that will please developers. Things such as strings in switch statements, multi-catch exception handling, try-with-resource statements, the new File System API, extensions of the JVM, support for dynamically-typed languages, the fork and join framework for task parallelism, and a few others will certainly be embraced by the community. Below I outline the features and provide examples where appropriate. A zip file containing code snippets used in this post can be downloaded here. Language enhancementsJava 7 includes a few new language features via Project Coin. These features are quite handy for a developer. Diamond OperatorYou may have noted on many occasions your IDE complaining of types when working with Generics. For example, if we have to declare a map of trades using Generics, we write the code as follows: Map<String, List<Trade>> trades = new TreeMap<String, List<Trade>> (); The not-so-nice thing about this declaration is that we must declare the types on both the sides, although the right-hand side seems a bit redundant. Can the compiler infer the types by looking at the left-hand-side declaration? Not unless you're using Java 7. In 7, it's written like this: Map<String, List<Trade>> trades = new TreeMap <> (); How cool is that? You don't have to type the whole list of types for the instantiation. Instead you use the Using strings in switch statementsSwitch statements work either with primitive types or enumerated types. Java 7 introduced another type that we can use in Switch statements: the Say we have a requirement to process a Trade based on its status. Until now we used to do this by using if-else statements. private void processTrade(Trade t) { String status = t.getStatus(); if (status.equalsIgnoreCase(NEW)) { newTrade(t); } else if (status.equalsIgnoreCase(EXECUTE)) { executeTrade(t); } else if (status.equalsIgnoreCase(PENDING)) { pendingTrade(t); } } This method of working on strings is crude. In Java 7, we can improve the program by utilizing the enhanced Switch statement, which takes a public void processTrade(Trade t) { String status = t.getStatus(); switch (status) { case NEW: newTrade(t); break; case EXECUTE: executeTrade(t); break; case PENDING: pendingTrade(t); break; default: break; } } In the above program, the status field is always compared against the case label by using the Automatic resource managementResources such as public void oldTry() { try { fos = new FileOutputStream("movies.txt"); dos = new DataOutputStream(fos); dos.writeUTF("Java 7 Block Buster"); } catch (IOException e) { e.printStackTrace(); } finally { try { fos.close(); dos.close(); } catch (IOException e) { // log the exception } } } However, Java 7 has introduced another cool feature to manage the resources automatically. It is simple in operation, too. All we have to do is declare the resources in the
try(resources_to_be_cleant){
// your code
}
The above method with the old try can finally can be re-written using this new feature as shown below:
public void newTry() {
try (FileOutputStream fos = new FileOutputStream("movies.txt");
DataOutputStream dos = new DataOutputStream(fos)) {
dos.writeUTF("Java 7 Block Buster");
} catch (IOException e) {
// log the exception
}
}
The above code also represents another aspect of this feature: working with multiple resources. The Behind the scenes, the resources that should be auto closed must implement Any resource that implements Numeric literals with underscoresNumerical literals are definitely eye strainers. I am sure you would start counting the zeroes like me if you've been given a number with, say, ten zeros. It's quite error prone and cumbersome to identify a literal if it's a million or a billion unless you count the places from right to left. Not anymore. Java 7 introduced underscores in identifying the places. For example, you can declare 1000 as shown below: int thousand = 1_000; or 1000000 (one million) as follows int million = 1_000_000 Note that binary literals are also introduced in this release too — for example "0b1" — so developers don't have to convert them to hexadecimals any more. Improved exception handlingThere are a couple of improvements in the exception handling area. Java 7 introduced multi-catch functionality to catch multiple exception types using a single catch block. Let's say you have a method that throws three exceptions. In the current state, you would deal them individually as shown in below: public void oldMultiCatch() { try { methodThatThrowsThreeExceptions(); } catch (ExceptionOne e) { // log and deal with ExceptionOne } catch (ExceptionTwo e) { // log and deal with ExceptionTwo } catch (ExceptionThree e) { // log and deal with ExceptionThree } } Catching an endless number of exceptions one after the other in a catch block looks cluttered. And I have seen code that catches a dozen exceptions, too. This is incredibly inefficient and error prone. Java 7 has brought in a new language change to address this ugly duckling. See the improved version of the method
public void newMultiCatch() {
try {
methodThatThrowsThreeExceptions();
} catch (ExceptionOne | ExceptionTwo | ExceptionThree e) {
// log and deal with all Exceptions
}
}
The multiple exceptions are caught in one catch block by using a '|' operator. This way, you do not have to write dozens of exception catches. However, if you have bunch of exceptions that belong to different types, then you could use "multi multi-catch" blocks too. The following snippet illustrates this: public void newMultiMultiCatch() { try { methodThatThrowsThreeExceptions(); } catch (ExceptionOne e) { // log and deal with ExceptionOne } catch (ExceptionTwo | ExceptionThree e) { // log and deal with ExceptionTwo and ExceptionThree } } In the above case, the ExceptionTwo and ExceptionThree belong to a different hierarchy, so you would want to handle them differently but with a single catch block. New file system API (NIO 2.0)Those who worked with Java IO may still remember the headaches that framework caused. It was never easy to work seamlessly across operating systems or multi-file systems. There were methods such as delete or rename that behaved unexpected in most cases. Working with symbolic links was another issue. In an essence, the API needed an overhaul. With the intention of solving the above problems with Java IO, Java 7 introduced an overhauled and in many cases new API. The NIO 2.0 has come forward with many enhancements. It's also introduced new classes to ease the life of a developer when working with multiple file systems. Working with PathA new A public void pathInfo() { Path path = Paths.get("c:\\Temp\\temp"); System.out.println("Number of Nodes:" + path.getNameCount()); System.out.println("File Name:" + path.getFileName()); System.out.println("File Root:" + path.getRoot()); System.out.println("File Parent:" + path.getParent()); } The console output would be: Number of Nodes:2 File Name:temp.txt File Root:c:\ File Parent:c:\Temp Deleting a file or directory is as simple as invoking a delete method on Files (note the plural) class. The The following delete method invocation throws Files.delete(path); Where as You can use other utility methods such as File change notificationsOne of my favorite improvements in the JDK 7 release is the addition of File Change Notifications. This has been a long-awaited feature that's finally carved into NIO 2.0. The The steps involved in implementing the API are:
Let's follow this via an example. We create a 1. Creating a WatchService watchService = FileSystems.getDefault().newWatchService(); 2. Obtain a path reference to your watchable directory. I suggest you parameterize this directory so you don't hard code the file name. path = Paths.get("C:\\Temp\\temp\\"); 3. The next step is to register the directory with the dirToWatch.register(watchService, ENTRY_CREATE, ENTRY_MODIFY, ENTRY_DELETE); These are 4. Initiate the infinite loop and start taking the events:
while(true)
{
WatchKey key = watchService.take(); // this would return you keys
}
5. Run through the events on the key: for (WatchEvent<?> event : key.pollEvents()) { Kind<?> kind = event.kind(); System.out.println("Event on " + event.context().toString() + " is " + kind); } For example, if you modify or delete the temp directory, you would see statement as shown below on the console respectively: Event on temp is ENTRY_MODIFY Event on temp is ENTRY_DELETE The relevant methods of the /** * This initiates the police */ private void init() { path = Paths.get("C:\\Temp\\temp\\"); try { watchService = FileSystems.getDefault().newWatchService(); path.register(watchService, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY); } catch (IOException e) { System.out.println("IOException"+ e.getMessage()); } } /** * The police will start making rounds */ private void doRounds() { WatchKey key = null; while(true) { try { key = watchService.take(); for (WatchEvent<?> event : key.pollEvents()) { Kind<?> kind = event.kind(); System.out.println("Event on " + event.context().toString() + " is " + kind); } } catch (InterruptedException e) { System.out.println("InterruptedException: "+e.getMessage()); } boolean reset = key.reset(); if(!reset) break; } } Fork and JoinThe 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. The core classes supporting the Fork-Join mechanism are We create an instance of ForkJoinPool pool = new ForkJoinPool(numberOfProcessors) Where numberOfProcessors = Runtime.getRunTime().availableProcessors(); However, the default The problem that needs to be solved is coded in a Here's how to create a
public class MyBigProblemTask extends RecursiveAction {
@Override
protected void compute() {
. . . // your problem invocation goes here
}
}
You have to override the compute method where in you need to provide the computing functionality. Now, provide this pool.invoke(task); Supporting dynamismJava is a statically typed language — the type checking of the variables, methods and return values is performed at compile time. The JVM executes this strongly-typed bytecode at runtime without having to worry about finding the type information. There's another breed of typed languages — the dynamically typed languages. Ruby, Python and Clojure are in this category. The type information is unresolved until runtime in these languages. This is not possible in Java as it would not have any necessary type information. There is an increasing pressure on Java folks improvise running the dynamic languages efficiently. Although it is possible to run these languages on a JVM (using In Java 7, a new feature called invokedynamic was introduced. This makes VM changes to incorporate non-Java language requirements. A new package, Wrapping upAs we've covered, Java 7 has a few bells and whistles that should put smiles on developers' faces, and the open-source collaboration and support for dynamic languages via JVM extensions should also be well received by those outside the Java community. Related: |
|||||
|
|||||
Comments: 17
SQLDenis [ 2 September 2011 07:56 AM]
Does Java 7 have true generics or is it still syntactic sugar ?
Martin Scharm [ 3 September 2011 04:43 AM]
Thanks a lot for this great overview! These are some good news ;-)
Swamy [ 5 September 2011 07:24 AM]
nice article with examples good overview.
Thanks,
Martijn Verburg [ 6 September 2011 11:15 AM]
Nice to see you do an article on this Madhu!
@SQLDenis Reified Generics are not in Java 7 and are likely not to be added to the language for several reasons including that it'll harm interoperability of non Java languages on the JVM.
For everyone else, I recommend trying out Madhu's samples and other Java 7 conversions of your code in Netbeans 7.0.1 as it has a very good hints system for doing so.
Happy hacking everyone!
Martijn (@karianna, @java7developer)
Raghu [ 6 September 2011 11:26 AM]
Nice Info... File change notifications is the most wanted feature.... but worried it has infinite loop.. :(
Emerson Cod [ 7 September 2011 07:20 AM]
You'r saying
"In the above program, the status field is always compared against the case label by using the String.equals() method."
this is wrong !
The compiler changes the strings to hashCode and the switch / case statements are running on the hashcode.
Friendly Comment [ 8 September 2011 04:33 AM]
It's nice to see a post with code on radar!
ashish jain [ 8 September 2011 10:18 AM]
Infinite loop for file changes polling, doesn't look good. Is there any settings for frequency of PATH check?
Madhusudhan Konda [ 8 September 2011 05:12 PM]
@SQLDenis, unfortunately Java Generics are syntactic sugar. @Martijn, thanks for the info.
@Emerson, I stand corrected - thanks. I believe it is a two step process - hashcode followed by string equality.
@Ashish Not to my knowledge, any one?
Anonymous [10 September 2011 03:22 AM]
@Ashish put in thread and sleep() in thread. Thread.Sleep()
Naveen Rao [20 September 2011 01:54 AM]
Good Article. Very informative and quickly learn-able as example code is also given. Thanks.
nanos [19 October 2011 10:15 PM]
Fork and join framework is not explained. Where fork/join takes place?
Ken [31 October 2011 10:23 AM]
Nice summary. Thanks.
ved Mishra [16 November 2011 04:58 AM]
Its has been a good experience whenever the Updates are coming in market,but still some complexity should be optimized using exception Handeling and all,well it's a gr8 launch for JAVA world.I'm happy to gain knowledge abt new features.......
Thanks
VED PRAKASH MISHRA
Victor [23 November 2011 05:14 AM]
Nice article, thanks.
I was looking for a brief of the new features in Java 7 and the info you provided is most helpful.
The nio package is great news indeed!!
@nagi [30 November 2011 02:02 AM]
Thank Mr. Madhu for ur survey on the features included in jdk7......
bob [15 February 2012 12:08 AM]
@Ashish as stated by another poster you wouldn't hit the loop without some sort of thread sleep.
Also you would probably thread out the methods to the files that you wished to work on rather than do them in the checking loop.
Saves performance issues and the inability to let a processor sleep or step down.
Actually for a file system you would be punishing it with anything less than a second, even worse if your monitoring a network drive.