Best Of Jdk 7
Upcoming SlideShare
Loading in...5
×
 

Best Of Jdk 7

on

  • 1,557 views

 

Statistics

Views

Total Views
1,557
Views on SlideShare
1,554
Embed Views
3

Actions

Likes
1
Downloads
18
Comments
0

1 Embed 3

http://www.linkedin.com 3

Accessibility

Categories

Upload Details

Uploaded via as OpenOffice

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Best Of Jdk 7 Best Of Jdk 7 Document Transcript

  • Quick Glance at the Upcoming Features in JDK 71. Switch with Strings value.2. Automatic Resource Management (ARM) try ( FileOutputStream fos = new FileOutputStream(file); InputStream is =url.openStream() )3. Dynamic InvokationIn Java 7, we’ll see a new feature, the JSR 292. This JSR add new method invocationmode : invokedynamic. With that new bytecode keyword, we can call method onlyknown at runtime.This JSR only impact the bytecode not the language. But with Java 7 we’ll see a newpackage java.dyn that use this new functionality. That package will improve theperformances of Java reflection and mainly the performances of the others languagesthat run in the JVM.(http://www.baptiste-wicht.com/2010/04/java-7-more-dynamics/ )4. ThreadLocalRandomA really simple but useful enhancement is the add of the ThreadLocalRandom class.This class is a random number generator linked to the current Thread. It seems that ifyou use this generator from two different thread, you will have two different randomgenerators. The generator is initialized with a generated seed that you cannot modify-(setSeed() throws anUnsupportedOperationException).You can use that class like that :long l = ThreadLocalRandom.current().nextLong(22L);If you always use this form, you have the guarantee that the random generator willnever be shared between two threads. Moreover, this new class provide methods togenerate a bounded numbers. By example, to generate a pseudo-random numberbetween 10, inclusive and 33, exclusive, you can type :int i = ThreadLocalRandom.current().nextInt(10, 33);5. java.utils.Objectspublic void setFoo(Foo foo){ this.foo = Objects.nonNull(foo);}
  • public void setBar(Bar bar){ this.foo = Objects.nonNull(bar, "bar cannot be null");}public class Bar { private Foo foo; private Bar parent; @Override public int hashCode(){ int result = 17; result = 31 * result + (foo == null ? 0 : foo.hashCode()); result = 31 * result + (parent == null ? 0 : parent.hashCode()); return result; }}With Java 7, we only have to do the following :public class Bar { private Foo foo; private Bar parent; @Override public int hashCode(){ return Objects.hash(foo, parent); }}6. Deep Equalsboolean equals(Object a, Object b) : Return true if the two arguments are null or theyare both not null and a.equals(b) return true, otherwise false.
  • • boolean deepEquals(Object a, Object b) : Almost the same as the first method except that if both a and b are arrays, the equality is evaluated using Arrays.deepEquals method.7. Better Exception Handling :} catch (FirstException ex) { logger.error(ex); throw ex;} catch (SecondException ex) { logger.error(ex); throw ex;}So now, with that new feature, you can do :} catch (FirstException | SecondException ex) { logger.error(ex); throw ex;}8. Allow -overriding static methods- new List interfaceList strings = new ArrayList();//...Collections.reverse(strings);>>>public interface List extends Collection { ... extension void reverse() default Collections.reverse;}So you can do :List strings = new ArrayList();//...strings.reverse();
  • 9. New File API(http://download.oracle.com/javase/tutorial/essential/io/legacy.html#mapping ) Prior to the JDK7 release, the java.io.File class was the mechanism used for file I/O, but it had several drawbacks. • Many methods didnt throw exceptions when they failed, so it was impossible to obtain a useful error message. For example, if a file deletion failed, the program would receive a "delete fail" but wouldnt know if it was because the file didnt exist, the user didnt have permissions, or there was some other problem. • The rename method didnt work consistently across platforms. • There was no real support for symbolic links. • More support for metadata was desired, such as file permissions, file owner, and other security attributes. • Accessing file metadata was inefficient. • Many of the File methods didnt scale. Requesting a large directory listing over a server could result in a hang. Large directories could also cause memory resource problems, resulting in a denial of service. • It was not possible to write reliable code that could recursively walk a file tree and respond appropriately if there were circular symbolic links.10. Asynchronous I/OArguably this id the most important feature in jdk 7 !!Here go the details from the following website ....http://www.baptiste-wicht.com/2010/04/java-7-new-io-features-asynchronous-operations-multicasting-random-access-with-jsr-203-nio-2/"... The new Asynchronous I/O API. Its name indicate all the purpose of this newfeatures, indeed enable Asynchronous I/O operations.This new channelsprovide asynchronous operations for both sockets and files.Of course, all that operations are non-blocking, but there is also blocking operationsthat you can do with all the asynchronous channels.All the asynchronous I/O operations have one of two forms : • The first one returns a java.util.concurrent.Future that represent the pending result. You can use that Future to wait for the I/O operations to finish.
  • • The second one is created using a CompletionHandler. That handler is invoked when the operation is has completed, like callbacks systems.So here are the examples of the two forms :The first form, using Future :AsynchronousFileChannel channel= AsynchronousFileChannel.open(Paths.get("Path to file"));ByteBuffer buffer = ByteBuffer.allocate(capacity);Future result = channel.read(buffer, 100); //Read capacity bytes from the file startingat position 100boolean done = result.isDone(); //Indicate if the result is already terminatedYou can also wait for completion :int bytesRead = result.get();Or wait with a timeout :int bytesRead = result.get(10, TimeUnit.SECONDS); //Wait at most 10 seconds onthe resultThe second form, using CompletionHandler :Future result = channel.read(buffer, 100, null, new CompletionHandler(){ public void completed(Integer result, Object attachement){ //Compute the result } public void failed(Throwable exception, Object attachement){ //Answer to the fail }});As you can see, you can give an attachement to the operation. This attachement isgiven to the CompletionHandler at the end of the operation. You can give null asattachement with no problem. But you can pass anything you want, like theConnection for a AsynchronousSocketChannel or the ByteBuffer for our read :Future result = channel.read(buffer, 100, buffer, new CompletionHandler(){ public void completed(Integer result, ByteBuffer buffer){ //Compute the result
  • } public void failed(Throwable exception, ByteBuffer buffer){ //Answer to the fail }});And as you can see, the form with the CompletionHandle gives also you a Futureelement representing the pending result, so you can merge the two forms.Here, are all the asynchronous channels available in NIO.2 : • AsynchronousFileChannel : An asynchronous channel for reading and writing from and to a file. This channel has no global positions, so each read/write operations needs a position to operate. You can access concurrently to different parts of the file using different threads. You have to specify the options (READ, WRITE, but not APPEND) when you open this channel. • AsynchronousSocketChannel : A simple asynchronous channel to a Socket. The connect, read/write and scatter/gather methods are all asynchronous. The read/write method supports timeouts. • AsynchronousServerSocketChannel : An asynchronous channel to a ServerSocket. The accept() method is asynchronous and the CompletionHandler is called when a connection has been accepted. The result of this kind of connection is an AsynchronousSocketChannel. • AsynchronousDatagramChannel : An channel to datagram-oriented socket. The read/write (connected) and receive/send (unconnected) methods are asynchronous."References :http://tech.puredanger.com/java7/http://www.baptiste-wicht.com/2010/04/java-7-updates-project-coin/