76
Java New Evolution Allan Huang @ esobi Inc.

Java New Evolution

Embed Size (px)

DESCRIPTION

 

Citation preview

Page 1: Java New Evolution

Java New Evolution

Allan Huang @ esobi Inc.

Page 2: Java New Evolution

Agenda

Java 5 Features Review Java 6 New Features Java 7 New Features

Page 3: Java New Evolution

Java Versions

Version 1.0 and 1.1 are named as JDK Version 1.2 to 1.4 are named as J2SE Version 1.5 are named as Java 5.0 JSR – Java Specification Request

Page 4: Java New Evolution

Versions and Naming

JDK 1.0 – 1996 JDK 1.1 – 1997 – JDBC, RMI, Reflection J2SE 1.2 – 1998 – Swing, Collections J2SE 1.3 – 2000 – HotSpot JVM, JavaSound, JNDI J2SE 1.4 – 2002 – assert, NIO, Web Start J2SE 5.0 (1.5) – 2004 – Generic, Autoboxing.. Java SE 6.0 (1.6) – 2006 – Rhino, JDBC 4.0… Java SE 7.0 (1.7) – 2011 – Small language

changes, API changes

Page 5: Java New Evolution

Java 5

Page 6: Java New Evolution

Java 5 Features Review (1)

Generics Allows a type or method to operate on objects of various

types while providing compile-time type safety to the Collections Framework and eliminates the drudgery of casting.

Page 7: Java New Evolution

Java 5 Features Review (2)

Enhanced for Loop This new language construct eliminates the drudgery and

error-proneness of iterators and index variables when iterating over collections and arrays.

Page 8: Java New Evolution

Java 5 Features Review (3)

Autoboxing / Unboxing Eliminates the drudgery of manual conversion between

primitive types (such as int) and wrapper types (such as Integer).

Page 9: Java New Evolution

Java 5 Features Review (4)

Typesafe Enums Allows you to create enumeration types with arbitrary

methods and fields, then It provides all the benefits of the Typesafe Enum pattern without the verbosity and the error-proneness.

Page 10: Java New Evolution

Java 5 Features Review (5)

Varargs Eliminates the need for manually boxing up argument lists

into an array when invoking methods that accept variable-length argument lists.

Page 11: Java New Evolution

Java 5 Features Review (6)

Static Import Lets you avoid qualifying static members with class names

without the shortcomings of the "Constant Interface Anti-pattern".

Page 12: Java New Evolution

Constant Interface Anti-pattern

Describes the use of an interface solely to define constants, and having classes implement that interface in order to achieve convenient syntactic access to those constants.

Anti-pattern Better Pattern

Page 13: Java New Evolution

Java 5 Features Review (7)

Annotations (Metadata) Lets you avoid writing Boilerplate Codes under many

circumstances by enabling tools to generate it from a "declarative" programming style - annotations in the source code.

Page 14: Java New Evolution

Java 5 Features Review (8)

Java Utility Scanner A simple text scanner which can parse primitive types and

strings using regular expressions. You can provide several resource types to read from.

Page 15: Java New Evolution

Java 5 Features Review (9)

Java Utility Formatter An interpreter for printf-style format strings that is like the

printf function in C language.

Page 16: Java New Evolution

Java Features Review (10-1)

Java Utility Concurrent The concurrency utilities packages provide a

powerful, extensible framework of high-performance threading utilities.

Advantages Reduced programming effort Increased performance Increased reliability Improved maintainability Increased productivity

Page 17: Java New Evolution

Java Features Review (10-2)

Java Utility Concurrent Task scheduling framework

Standardizes invocation, scheduling, execution, and control of asynchronous tasks according to a set of execution policies.

Fork / join framework Designs to efficiently run a large number of tasks using a pool

of worker threads. Concurrent collections

Adds new collections classes and high-performance, concurrent implementations, e.g. Queue, BlockingQueue, BlockingDeque.

Page 18: Java New Evolution

Java Features Review (10-3)

Java Utility Concurrent Atomic variables

A small toolkit of classes that support lock-free thread-safe programming on single variables.

Synchronizers General purpose synchronization classes that facilitate

coordination between threads. Locks

Provides a framework for locking and waiting for conditions that is distinct from built-in synchronization and monitors.

Nanosecond-granularity timing Returns the current value of the running Java Virtual

Machine's high-resolution time source, in nanoseconds.

Page 19: Java New Evolution

Java Utility Concurrent

Page 20: Java New Evolution

Java 6

Page 21: Java New Evolution

Java 6 New Features (1)

Pluggable Annotation Processing API (JSR 269) Annotations aimed in providing a Meta-Data

Facility to the Java A Customized Annotation Processor which can be

plugged-in to the code to operate on the set of annotations that appear in a source file.

Class-Level Annotation @Target(value = {ElementType.TYPE})

Method-Level Annotation @Target(value = {ElementType.METHOD})

Page 22: Java New Evolution

Pluggable Annotation Processing API Examples

Class-Level Annotation

Method-Level Annotation

Page 23: Java New Evolution

Java 6 New Features (2-1)

Common Annotations (JSR 250) Define a set of annotations that address common

semantic concepts and therefore can be used by many Java EE and Java SE components.

Avoid applications defining their own annotations which will result in having larger number of duplicates.

Page 24: Java New Evolution

Java 6 New Features (2-2)

Common Annotations (JSR 250) @Generated

Marks sources that have been generated @Resource, @Resources, @DataSourceDefinition,

@ManagedBean Declares a reference to one / many resources

@PostConstruct, @PreDestroy Get executed after dependency injection is done or called before the

instance is removed @Priority

Indicate in what order the classes should be used @DeclareRoles, @RoleAllowed, @PermitAll, @DenyAll,

@RunAs Role Based Annotations about security

Page 25: Java New Evolution

Java 6 New Features (3)

Java Architecture for XML Binding - JAXB 2.0 (JSR 222) A Mapping Technology allows developers to map

Java classes to XML representations. Two main features are capable of Marshalling

Java objects into XML and Un-marshalling XML back into Java objects.

Page 26: Java New Evolution

JAXB Examples

Page 27: Java New Evolution

Java 6 New Features (4)

Java API for XML Based Web Services – JAX-WS 2.0 (JSR 224) Define a set of APIs for creating web services in SOAP,

and provide many annotation to simplify the development and deployment for both web service clients and web service providers (endpoints).

Java-to-WSDL mapping determines which Java method gets invoked and how that SOAP message is mapped to the method’s parameters, and also determines how the method’s return value gets mapped to the SOAP response.

Page 28: Java New Evolution

JAX-WS Architecture

WS Action in Server-SideWS Action Flow

Page 29: Java New Evolution

JAX-WS ExamplesService Endpoint Interface Service Endpoint Publisher

Web Service ClientService Endpoint Implementation

Page 30: Java New Evolution

Java 6 New Features (5-1)

Web Services Metadata for Java (JSR 181) Annotate a Web Service implementation class or

a Web Service interface, and create portable Java Web Services from a simple POJO class by adding annotations

Benefits Provide a simplified model for developing Web Services Abstract the implementation details Achieve robustness, easy maintenance, and high

interoperability

Page 31: Java New Evolution

Java 6 New Features (5-2)

Web Services Metatdata for Java (JSR 181) @WebService

Marks a Java class as implementing a Web Service or marks a service endpoint interface (SEI) as implementing a Web Service interface

@WebMethod Denotes a method that is a Web Service operation

@OneWay Denotes a method as a Web Service one-way operation that

only has an input message and no output message @WebParam

Customizes the mapping of an individual parameter to a Web Service message part and XML element

Page 32: Java New Evolution

Java 6 New Features (5-3)

Web Services Metatdata for Java (JSR 181) @WebResult

Customizes the mapping of a return value to a WSDL part or XML element

@HandleChain Associates the Web Service with an externally defined handler

chain @SOAPBinding

Specifies the mapping of the Web Service onto the SOAP message protocol

Page 33: Java New Evolution

Java 6 New Features (6-1)

Streaming API for XML – StAX (JSR 173) StAX API exposes methods for iterative, event-

based processing of XML documents. StAX is a Pull style API, SAX is a Push style API. StAX can do both XML reading and writing, SAX

can only do XML reading. StAX allows Sub-parsing / Delegation StAX has support for XML Writing StAX has not support for Schema Validation

Page 34: Java New Evolution

Java 6 New Features (6-2)

Streaming API for XML – StAX (JSR 173) StAX is really two distinct API sets

A Cursor API is likes JDBC ResultSet An Iterator API is likes Iterator interface

Iterator API can keep track of the previous event, but Cursor can’t do that. javax.xml.stream.XMLEventReader

Cursor API is more memory-efficient than Iterator API. javax.xml.stream.XMLStreamReader

Page 35: Java New Evolution

DOM, SAX, StAXDOM SAX

SAX vs. StAXStAX

Page 36: Java New Evolution

StAX API ExamplesRead from XML Write to XML

Page 37: Java New Evolution

Java 6 New Features (7)

XML Digital Signature (JSR 105) Digital Signature

A value computed with a cryptographic algorithm and appended to a data object in such a way that any recipient of the data can use the signature to verify the data's origin and integrity.

Define a standard set of APIs for generating and validating XML Digital Signatures specified by W3C.

It defines a process and a format for generating digital signatures in the XML format, and it can sign arbitrary data, whether it is XML or binary.

Page 38: Java New Evolution

XML Digital Signature Examples

Page 39: Java New Evolution

Java 6 New Features (8)

Java Class File Specification Update (JSR 202) This JSR will make incremental updates to the

Java class file format. This will principally consist of increasing certain

class file size limits and adding support for split verification.

Page 40: Java New Evolution

Java 6 New Features (9-1)

Java Compiler API (JSR 199) Allow a Java program to select and invoke a Java compiler

programmatically, then compile java source files. Web and application servers can depend on this API

exhaustively to provide compilation activities of the dynamically created Java source files.

Page 41: Java New Evolution

Java 6 New Features (9-2)

Java Compiler API (JSR 199) JavaFileManager

Create output files, scan for the input files, and cache them for better performance.

The content of Input files managed may come from a physical file in a hard-disk, in-memory or a remote socket.

DiagnosticListener Report the diagnostics (error, warning or information)

that may occur during the compilation process within a program.

Page 42: Java New Evolution

Java 6 New Features (10-1)

JDBC 4.0 (JSR 221) Auto-loading of JDBC driver class

No need for Class.forName(“DriverName”) Support Service Provider Mechanism via

META-INF/services/java.sql.Driver Find unique JDBC driver via java.util.ServiceLoader

RowID data type support A kind of pseudo column for Oracle and DB2, etc. RowIDs are unique IDs for rows in a given table. RowIDs are the fastest means of accessing particular

rows. RowIDs can be used to see how a table is organized.

Page 43: Java New Evolution

Java 6 New Features (10-2)

JDBC 4.0 (JSR 221) Connection management enhancements

Improved connection state tracking SQL Exception handling enhancements

New SQLException Sub-Classes: Transient, Recoverable, Non-Transient exceptions

Enhanced For-Each Loop in Iterable SQLException SQLXML data type support for SQL:2003

Correspond to the XML data type in the database Use an DOM or SAX representation of XML data

Page 44: Java New Evolution

Java 6 New Features (10-3)

JDBC 4.0 (JSR 221) Enhanced Blob / Clob functionality

New corresponding methods for BLOB, CLOB, NCLOB A new method free() for release of resource

National Character Set support New corresponding methods for NCHAR, NVARCHAR,

LONGNVARCHAR, NCLOB A bundled Database – Apache Derby

An open source relational database implemented entirely in Java

Not support Annotation-Based SQL Queries

Page 45: Java New Evolution

JDBC 4.0 Examples

SQLXMLService Loader

Page 46: Java New Evolution

Java 6 New Features (11-1)

JavaScript Support – Rhino (JSR 223) Mozilla Rhino Script Engine that supports various

Scripting Languages is integrated into the Java. Rhino converts JavaScript scripts into classes,

and it’s intended to be used in server-side apps without built-in support for the Web browser objects.

Page 47: Java New Evolution

Java 6 New Features (11-2)

JavaScript Support – Rhino (JSR 223) Convenience

Create new variables without declaring the variable type, and reuse variables to store objects of different types.

Developing rapid prototypes Avoid the edit-compile-run cycle and just use edit-run!

Application extension/customization You can "externalize" parts of your application.

"Command line" shells for applications Admins and deployers frequently prefer command line

tools for debugging, runtime / deploy time configuration.

Page 48: Java New Evolution

Java 6 New Features (11-3)

JavaScript Support – Rhino (JSR 223) Language Bindings provides mechanisms for

establishing communications between the Java code and the script code.

ScriptEngineManager class provides mechanisms for Searching and Adding Scripting Engines into the Java Platform.

Page 49: Java New Evolution

JavaScript Support Examples

Page 50: Java New Evolution

Java 7

Page 51: Java New Evolution

Java 7 New Features (1)

Binary Literals The types byte, short, int, and long can also be expressed

using the binary number system. To specify a binary literal, add the prefix 0b or 0B to the

number.

Page 52: Java New Evolution

Java 7 New Features (2)

Underscores in Numeric Literals Any number of underscore characters (_) can appear

anywhere between digits in a numerical literal.

Page 53: Java New Evolution

Java 7 New Features (3)

Strings in switch Statements Use the String class in the expression of a switch

statement.

Page 54: Java New Evolution

Java 7 New Features (4)

Type Inference for Generic Instance Creation Replace the type arguments required to invoke the

constructor of a generic class with an empty set of type parameters (<>).

This pair of angle brackets is informally called the diamond.

Page 55: Java New Evolution

Java 7 New Features (5)

Improved Compiler Warnings and Errors When Using Non-Reifiable Formal Parameters with Varargs Methods The complier generates a warning at the

declaration site of a varargs method or constructor with a non-reifiable varargs formal parameter.

Page 56: Java New Evolution

Java 7 New Features (5-1)

Heap Pollution A non-reifiable type is a type that is not completely

available at runtime, and type erasure removes information from parameterized types at compile-time.

Heap pollution occurs when a variable of a parameterized type refers to an object that is not of that parameterized type.

Page 57: Java New Evolution

Java 7 New Features (5-2)

Variable Arguments Methods and Non-Reifiable Formal Parameters Compiler encounters a varargs method, it translates the

varargs formal parameter into an array. Java does not permit the creation of arrays of

parameterized types.

Page 58: Java New Evolution

Java 7 New Features (5-3)

Potential Vulnerabilities of Varargs Methods with Non-Reifiable Formal Parameters Compiler has generated a warning when it translated the

varargs formal parameter to the formal parameter.

Page 59: Java New Evolution

Java 7 New Features (5-4)

Suppressing Warnings from Varargs Methods with Non-Reifiable Formal Parameters If you declare a varargs method with

parameterized parameters, and you ensure that the method does not throw a ClassCastException or other similar exception, you can suppress the warning that the compiler generates.

Page 60: Java New Evolution

Suppressing Compiler Warnings Add @SafeVarargs to the static and non-constructor

method declarations Add @SuppressWarnings(“unchecked") to the

method declaration Use the compiler non-standard option -Xlint:varargs

Page 61: Java New Evolution

Java 7 New Features (6)

The try-with-resources Statement A try statement declare one or more resources and

ensures that each resource is automatically closed at the end of the statement.

A resource is an object that must be closed after the program is finished with it, and it implements java.lang.AutoClosable.

Page 62: Java New Evolution

Java 7 New Features (7)

Handling More Than One Type of Exception A single catch block can handle more than one type of

exception that can reduce code duplication and lessen the temptation to catch an overly broad exception.

Page 63: Java New Evolution

Java 7 New Features (8)

Rethrowing Exceptions with More Inclusive Type Checking Performs more precise analysis of rethrown exceptions that

enables you to specify more specific exception types in the throws clause of a method declaration.

Page 64: Java New Evolution

Java 7 New Features (9-1)

Java New I/O 2.0 – NIO.2 (JSR 203) A new file system and path abstraction

Provides new file system functionalities to perform over a file, a directory, or a link.

Metadata File Attributes Provides access to metadata file attributes through the

java.nio.file.attribute package. Symbolic Links and Hard Links

Provides support for both hard links and symbolic links (soft link).

Each method of the Path class knows how to detect a link and will behave in the default manner.

Page 65: Java New Evolution

Java 7 New Features (9-2)

Hard Link vs. Symbolic Link (Soft Link) A hard link is an actual physical entity representing the link. A symbolic link is a pointer to a physical entity. Symbolic links function similar to the short-cuts in a DOS

based operating system.

Page 66: Java New Evolution

Java 7 New Features (9-3)

Java New I/O 2.0 – NIO.2 (JSR 203) New API for Files and Directories

Performs the most common tasks for managing files and directories, such as create, read, write, move, delete.

The FileVisitor Interface Traverses a file tree via FileVisitor, such as finding,

copying, deleting, and moving files. Monitoring via Watch Service API

A thread-safe service that is capable of watching objects for changes and events.

Monitors a directory for changes to its content through actions such as create, delete, and modify.

Page 67: Java New Evolution

Java 7 New Features (9-4)

Java New I/O 2.0 – NIO.2 (JSR 203) New powerful Random Access Files

Provides facilities such as mapping a region of the file directly into memory for faster access, locking a region of the file, etc.

Networking with the Sockets APIs Updating existing classes with new methods and adding

new interfaces/classes for writing TCP/UDP-based applications.

The Asynchronous Channel API A channel that supports asynchronous I/O operations for

use by multiple concurrent threads.

Page 68: Java New Evolution

NIO.2 Examples (1)

Change Notification

Selectors Help Multiplex

Page 69: Java New Evolution

NIO.2 Examples (2)

Memory Mapping Char Encoding & Searching

Page 70: Java New Evolution

Java 7 New Features (10-1)

Dynamically Typed Languages Support (JSR 292) Static Language (Static type-checking)

The process of verifying the type safety of a program based on analysis of a program's source code.

Dynamic Language (Dynamic type-checking) The process of verifying the type safety of a program at

runtime. Developers are increasingly using pre-existing runtime

environments to host their languages. Allows an easier mix and match approach of dynamic and

static languages on the JVM.

Page 71: Java New Evolution

Java 7 New Features (10-2)

Dynamically Typed Languages Support (JSR 292) Adds a new bytecode instruction - InvokeDynamic, to allow

method invocation relying on dynamic type checking. Three major features

Dynamic Invocation This instruction is used to call methods which have linkage and

dispatch semantics defined by non-Java languages. Method Handle Invocation

A method handle is a typed, directly executable reference to an underlying method, constructor, field, or similar low-level operation, with optional transformations of arguments or return values.

Exotic (non-Java) Identifiers An exotic identifier is introduced by a hash mark (# symbol), which is

immediately followed by a string literal.

Page 72: Java New Evolution

Dynamically Typed Language Examples

Page 73: Java New Evolution

Reference (1)

Java Programming Language Enhancements Constant interface Boilerplate Code Wikipedia Concurrency Utilities Overview Introduction to Java 6.0 New Features, Part–1 Java SE 6 Features and Enhancements JSR 250 Wikipedia Java Architecture for XML Binding Wikipedia Tutorial: Review of JAX-WS Server Side for the Web Ser

vices Developer Exam JAX-WS Hello World Example – RPC Style

Page 74: Java New Evolution

Reference (2)

Java API for XML Web Services Wikipedia Web Services Metadata for Java Wikipedia JAX-WS annotations Mapping Java Objects and XML Documents using JAXB

in Java 6.0 Programming With the Java XML Digital Signature API The Java 6.0 Compiler API Java & XML Tutorial: StAX StAX API StAX the odds with Woodstox JDBC 4.0 API in Java 6.0 JDBC 4.0 Enhancements in Java SE 6

Page 75: Java New Evolution

Reference (3)

Rhino (JavaScript Engine) Wikipedia Java Scripting Programmer’s Guide Java SE 7 Features and Enhancements JDK7: Part 1- The power of java 7 NIO.2 Five ways to maximize Java NIO and NIO.2 What is the difference between symbolic link and hard

link JSR 292 and the Multi-lingual JVM An Introduction To Programming Type Systems Type System Wikipedia InterfaceDynamic - Da Vinci Machine Project

Page 76: Java New Evolution

Q&A