• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Java se7 features

Java se7 features



This presentation provides overview of Java SE 7 new features, mainly concentrates on Project Coin, NIO.2 updates

This presentation provides overview of Java SE 7 new features, mainly concentrates on Project Coin, NIO.2 updates



Total Views
Views on SlideShare
Embed Views



1 Embed 9

https://duckduckgo.com 9



Upload Details

Uploaded via as Microsoft PowerPoint

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.

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
Post Comment
Edit your comment
  • “Project Coin is a suite oflanguage and library changesto make things programmers doeveryday easier.”“Small” languagechangesLanguage Level, not VMRemove extra text to make programs more readable• Encourage writing programs that are more reliable• Integrate well with past and future changesProject Coin in Action:Using New Java SE 7 Language Features in Real Code,Easy for the programmer, more work for the compiler!
  • http://docs.oracle.com/javase/7/docs/technotes/guides/language/type-inference-generic-instance-creation.htmlYou can replace the type arguments required to invoke the constructor of a generic class with an empty set of type parameters (<>) as long as the compiler can infer the type arguments from the context. This pair of angle brackets is informally called the diamond.In Java SE 7, you can substitute the parameterized type of the constructor with an empty set of type parameters (<>): Note that to take advantage of automatic type inference during generic class instantiation, you must specify the diamond. In the following example, the compiler generates an unchecked conversion warning because the HashMap() constructor refers to the HashMap raw type, not the Map> type:
  • In Java SE 7 and later, a single catch block can handle more than one type of exception. This feature can reduce code duplication and lessen the temptation to catch an overly broad exception.The catch clause specifies the types of exceptions that the block can handle, and each exception type is separated with a vertical bar (|).Note: 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.Bytecode generated by compiling a catch block that handles multiple exception types will be smaller (and thus superior) than compiling many catch blocks that handle only one exception type each. A catch block that handles multiple exception types creates no duplication in the bytecode generated by the compiler; the bytecode has no replication of exception handlers.
  • This examples's try block could throw either FirstException or SecondException. Suppose you want to specify these exception types in the throws clause of the rethrowException method declaration. In releases prior to Java SE 7, you cannot do so. Because the exception parameter of the catch clause, e, is type Exception, and the catch block rethrows the exception parameter e, you can only specify the exception type Exception in the throws clause of the rethrowException method declaration.However, in Java SE 7, you can specify the exception types FirstException and SecondException in the throws clause in the rethrowException method declaration. The Java SE 7 compiler can determine that the exception thrown by the statement throw e must have come from the try block, and the only exceptions thrown by the try block can be FirstException and SecondException. Even though the exception parameter of the catch clause, e, is type Exception, the compiler can determine that it is an instance of either FirstException or SecondException:
  • http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.htmlThe try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.In this example, the resource declared in the try-with-resources statement is a BufferedReader. The declaration statement appears within parentheses immediately after the try keyword. The class BufferedReader, in Java SE 7 and later, implements the interface java.lang.AutoCloseable. Because the BufferedReader instance is declared in a try-with-resource statement, it will be closed regardless of whether the try statement completes normally or abruptly (as a result of the method BufferedReader.readLine throwing an IOException).However, in this example, if the methods readLine and close both throw exceptions, then the method readFirstLineFromFileWithFinallyBlock throws the exception thrown from the finally block; the exception thrown from the try block is suppressed. In contrast, in the example readFirstLineFromFile, if exceptions are thrown from both the try block and the try-with-resources statement, then the method readFirstLineFromFile throws the exception thrown from the try block; the exception thrown from the try-with-resources block is suppressed. In Java SE 7 and later, you can retrieve suppressed exceptions; see the section Suppressed Exceptions for more information.Throwable.getSuppressedSee the Javadoc of the AutoCloseable and Closeable interfaces for a list of classes that implement either of these interfaces. The Closeable interface extends the AutoCloseable interface. The close method of the Closeable interface throws exceptions of type IOException while the close method of the AutoCloseable interface throws exceptions of type Exception. Consequently, subclasses of the AutoCloseable interface can override this behavior of the close method to throw specialized exceptions, such as IOException, or no exception at all.--------------------------"One shortcoming of the construct is that it does not provide a way for the programmer to indicate that exceptions thrown when closing a resource should be ignored"
  • The Java switch statement is compiled into the JVM bytecodetableswitch or lookupswitch. Both of these bytecodes require that the case values be unique, 32-bit, integer, compile-time constants.The tableswitch and lookupswitch instructions both include one default branch offset and a variable-length set of case value/branch offset pairs.Both instructions pop the key (the value of the expression in the parentheses immediately following the switch keyword) from the stack.The key is compared with all the case values:If a match is found, the branch offset associated with the case value is taken. If no match is found, the default branch offset is taken. If you attempt to use a long, float, or double as a switch key, your program won't compile.http://www.artima.com/underthehood/flowP.html
  • Binary literals can make relationships among data more apparent than they would be in hexadecimal or octal. For example, each successive number in the following array is rotated by one bit:public static final int[] phases = { 0b00110001, 0b01100010, 0b11000100, 0b10001001, 0b00010011, 0b00100110, 0b01001100, 0b10011000}In hexadecimal, the relationship among the numbers is not readily apparent:public static final int[] phases = { 0x31, 0x62, 0xC4, 0x89, 0x13, 0x26, 0x4C, 0x98}
  • The following examples demonstrate valid and invalid underscore placements (which are highlighted) in numeric literals:float pi1 = 3_.1415F; // Invalid; cannot put underscores adjacent to a decimal pointfloat pi2 = 3._1415F; // Invalid; cannot put underscores adjacent to a decimal pointlong socialSecurityNumber1 = 999_99_9999_L; // Invalid; cannot put underscores prior to an L suffixint x1 = _52; // This is an identifier, not a numeric literalint x2 = 5_2; // OK (decimal literal)int x3 = 52_; // Invalid; cannot put underscores at the end of a literalint x4 = 5_______2; // OK (decimal literal)int x5 = 0_x52; // Invalid; cannot put underscores in the 0x radix prefixint x6 = 0x_52; // Invalid; cannot put underscores at the beginning of a numberint x7 = 0x5_2; // OK (hexadecimal literal)int x8 = 0x52_; // Invalid; cannot put underscores at the end of a numberint x9 = 0_52; // OK (octal literal)int x10 = 05_2; // OK (octal literal)int x11 = 052_; // Invalid; cannot put underscores at the end of a number
  • http://docs.oracle.com/javase/7/docs/technotes/guides/language/non-reifiable-varargs.htmlhttp://codeidol.com/java/javagenerics/Reification/Reifiable-Types/Note: In Java SE 5 and 6, it is the responsibility of the programmer who calls a varargs method that has a non-reifiablevarargs formal parameter to determine whether heap pollution would occur. However, if this programmer did not write such a method, he or she cannot easily determine this. In Java SE 7, it is the responsibility of the programmer who writes these kinds of varargs methods to ensure that they properly handle the varargs formal parameter and ensure heap pollution does not occur.In Java, we say that a type is reifiable if the type is completely represented at run time that is, if erasure does not remove any useful information. To be precise, a type is reifiable if it is one of the following:A primitive type (such as int)A nonparameterized class or interface type(such as Number, String, or Runnable)A parameterized type in which all type arguments are unbounded wildcards(such as List, ArrayList, or Map)A raw type (such as List, ArrayList, or Map)An array whose component type is reifiable(such as int[], Number[], List[], List[], or int[][])A type is not reifiable if it is one of the following:A type variable (such as T)A parameterized type with actual parameters(such as List, ArrayList, or Map)A parameterized type with a bound(such as List or Comparable)So the type List is not reifiable, even though it is equivalent to List. Defining reifiable types in this way makes them easy to identify syntactically.
  • Preview versions of classes targeted for Java 7. Includes a fine-grained parallel computation framework: ForkJoinTasks and their related support classes provide a very efficient basis for obtaining platform-independent parallel speed-ups of computation-intensive operations. They are not a full substitute for the kinds of arbitrary processing supported by Executors or Threads. However, when applicable, they typically provide significantly greater performance on multiprocessor platforms. Candidates for fork/join processing mainly include those that can be expressed using parallel divide-and-conquer techniques: To solve a problem, break it in two (or more) parts, and then solve those parts in parallel, continuing on in this way until the problem is too small to be broken up, so is solved directly. The underlying work-stealing framework makes subtasks available to other threads (normally one per CPU), that help complete the tasks. In general, the most efficient ForkJoinTasks are those that directly implement this algorithmic design pattern.
  • The bounds checks slows the performance when compared to native languages. In JDK7, there is a JVM performance improvement on array accesses.
  • Lambdas – support for lambda mathematical function, lambda expressionsa little snippet of code (function) that can be passed as argument of some method for subsequent execution

Java se7 features Java se7 features Presentation Transcript

  • JAVA SE 7 Features Kumaraswamy Gowda May 2012
  • JDK 7 Release – Session agenda Project Coin NIO.2 Concurrency and collections updates Performance JDK 7 release More features from JDK 7 release A glimpse of Java SE 8 Q&A1
  • Project Coin The Six Coin Features and How They Help Easier to use generics Diamond Varargs warnings More concise error handling Multi-catch try-with-resources (aka ARM or TWR) Consistency and clarity Strings in switch Literal improvements Binary literals Underscores in literals2
  • Diamond syntax  Type Inference for Generic Instance Creation3
  • Multi Catch and Final Re-throw Handling More Than One Type of Exception in a single catch blockNote: If a catch block handles more than one exception type, then the catchparameter is implicitly final. In this example, the catch parameter ex is final andtherefore you cannot assign any value to it within the catch block.4
  • Multi Catch and Final Re-throwContd.  Rethrowing Exceptions with More Inclusive Type Checking5
  • try-with-resources Prior JDK 7  code in finally block, to ensure that a resource is closed regardless of whether the try statement completes normally or abruptly. The code is a bit messy!6
  • try-with-resources Cont. JDK 7 introduces a try-with-resources statement, which ensures that each of the resources in try(resourses) is closed at the end of the statement. This results in cleaner code. Note: A try-with-resources statement can have catch and finally blocks just like an ordinary try statement. In a try-with-resources statement, any catch or finally block is run after the resources declared have been closed. Suppressed Exceptions Throwable.getSuppressed Classes That Implement the AutoCloseable or Closeable Interface7
  • Strings in switch  Nothing much to explain here, the title says it all.  Previous versions of Java, the argument of switch had to be only of the following primitive data types: byte, short, char, int, or enum  Starting from JDK 7, you can use arguments of type String in the expression of a switch statement.  How about LONG in switch?8
  • Binary Literals  Integral types (byte, short, int, and long) can also be expressed using the binary number system  Add the prefix 0b or 0B to the number9
  • Underscores in Numeric Literals How much is 10000000000? And now 10_000_000_000? You can place underscores only between digits; you cannot place underscores in the following places: At the beginning or end of a number Adjacent to a decimal point in a floating point literal Prior to an F or L suffix In positions where a string of digits is expected10
  • Simplified vararg methods invocation Heap Pollution  Non-reifiable types  parameterized types, such as ArrayList<Number> and List<String>  Occurs when a variable of a parameterized type refers to an object that is not of that parameterized type  During type erasure, the types ArrayList<Number> and List<String> become ArrayList and List, respectively. In JDK 1.7  @SafeVarargs has been introduced to suppress such exception.11
  • vararg methods invocation Contd.12
  • Project Coin – Design complexity vs Implementation Effort13
  • Project Coin support in IDEs  Pick an IDE, any IDE IntelliJ IDEA 10.5 and later http://blogs.jetbrains.com/idea/2011/02/announcin g-intellij-idea-105-with-full-java-7-support/ Eclipse 3.7.1 and later http://www.eclipse.org/jdt/ui/r3_8/Java7news/what s-new-java-7.html NetBeans 7.0 and later http://netbeans.org/kb/docs/java/javase-jdk7.html14
  • NIO.2 Navigation Helpers  Two key navigation Helper Types: Class java.nio.file.Paths Exclusively static methods to return a Path by converting a string or Uniform Resource Identifier (URI) Interface java.nio.file.Path Used for objects that represent the location of a file in a file system, typically system dependent. Typical use case: Use Paths to get a Path. Use Files to do stuff.15
  • NIO.2 Features –Files Helper Class  Class java.nio.file.Files  Exclusively static methods to operate on files, directories and other types of files Files helper class is feature rich: Copy Create Directories Create Files Create Links Use of system “temp” directory Delete Attributes –Modified/Owner/Permissions/Size, etc. Read/Write  Files.move(src, dst);  Files.copy(src, dst,StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING);16
  • NIO.2 Directories  Directory support in NIO.2 using DirectoryStream  Uses less resources  Smooth out response time for remote file systems  Implements Iterable and Closeable for productivity17
  • NIO.2 Symbolic Links  Path and Files are “link aware”.  One could create symbolic link or hard link from one path to another.18
  • NIO.2 Walking A File TreeA FileVisitor interface makes walking a file tree for search, or performing actions. SimpleFileVisitor implements preVisitDirectory(T dir, BasicFileAttributes attrs); visitFile(T dir, BasicFileAttributes attrs); visitFileFailed(T dir, IOException exc); postVisitDirectory(T dir, IOException exc);19
  • NIO.2 Watching A Directory  Create a WatchService “watcher” for the filesystem Register a directory with the watcher “Watcher” can be polled or waited on for eventsEvents raised in the form of Keys Retrieve the Key from the Watcher Key has filename and events within it for create/delete/modify Ability to detect event overflows20
  • NIO.2 many more… Custom FileSystems Provider registration method may depend on JSR-277 Provider is a factory for FileSystem, FileRef and FileChannel objects Need not be tied to a “real” filesystem Zip file, CD-ROM image, ram disk, flash rom, etc Multiple/alternate views of same underlying files Hide sensitive files, read-only views, path munging, etc Filesystem provider for zip/jar archives Asynchronous I/O Buffers, Sockets and File I/O Mostly small additions for completeness Multicast is the big new feature21
  • Concurrency and Collections updates platform-independent parallel speed-ups of computation-intensive operations not a full substitute for the kinds of arbitrary processing supported by Executors or Threads provide significantly greater performance on multiprocessor platforms22
  • Concurrency: Recursive Taskexample23
  • Concurrency: Recursive Task example Cont.24
  • Performance - JDK 7 The JDK 7 delivers quite a speed boost over JDK 6 array accesses25
  • More features of Java SE 7 Support for dynamically-typed languages (InvokeDynamic) Concurrency and collections updates SCTP (Stream Control Transmission Protocol) SDP (Sockets Direct Protocol) JDBC 4.1 Enhanced Mbeans Update the XML stack client XRender pipeline for Java 2D Create new platform APIs for 6u10 graphics features Nimbus look-and-feel for Swing Swing JLayer component Gervill sound synthesizer  and few more… JavaDoc Improvements CSS for JavaDoc -stylesheet.css26
  • Java SE 8  Due to land Spring / Summer 2013 Main Features Lambdas (aka Closures) New Date and Time APIs Jigsaw (modularisation) Also: Type Annotations Coin Part 2 Ongoing work to merge VMs Getting rid of PermGen27
  • Java SE 8 Cont. Creating collections like Arrays and Index based access Advanced Example Creating immutable collection28
  • References for resources  JDK 7 features:  http://openjdk.java.net/projects/jdk7/features/  http://www.oracle.com/technetwork/java/javase/jdk7-relnotes- 418459.html  Project coin:  http://docs.oracle.com/javase/7/docs/technotes/guides/language/ enhancements.html#javase7  Support for Dynamically Typed Languages in the Java Virtual Machine  http://java.sun.com/developer/technicalArticles/DynTypeLang/  NIO.2  http://docs.oracle.com/javase/7/docs/technotes/guides/io/enhanc ements.html#729
  • References for JDK8  Project Lambda http://openjdk.java.net/projects/lambda/  Project Lambda: Straw-Man Proposal http://cr.openjdk.java.net/~mr/lambda/straw-man/30
  • Java 7 New Features Questions?31