千呼萬喚始出來的 Java SE 7

Post on 05-Jul-2015

1.230 views 7 download

description

2011 Java TWO

Transcript of 千呼萬喚始出來的 Java SE 7

千呼萬喚始出來的

Java SE 7

● 林信良

● caterpillar@openhome.cc

● http://openhome.cc

議程

• Java 進化史

• JSR334 / Coin 專案

• Unicode 6.0.0、JDBC 4.1

• JSR203 / NIO.2

• JSR166y / Concurrency Updates

• JSR292 / Da Vinci Machine 專案

Java 進化史

2002/02/13

Java 進化史

2004/09/29

Java 進化史

2006/12/11

Java 進化史

2011/07/28

A / B 計畫

• JDK 7 Features updated ! Plan B has

apparently been approved

– http://www.baptiste-wicht.com/2010/09/jdk-7-

features-updated-plan-b-is-apparently-here/

JDK7 ...

Jigsaw

λ Language support for collections

Annotations on Java types

JDK7 有...

• JDK 7 Features

– http://openjdk.java.net/projects/jdk7/features/

NIO.2

Coin Invoke

Dynamic

Concurrency

Updates

JSR334 / Coin 專案

Small language enhancements

• Strings in switch

• Binary integral literals and underscores in

numeric literals

• Multi-catch and more precise rethrow

• Improved Type Inference for Generic

Instance Creation (diamond)

• try-with-resources statement

• Simplified Varargs Method Invocation

Strings in if-else

Strings in switch

反組譯...

先用 hashCode()

再用 equals()

Binary integral literals and

underscores in numeric literals

• Binary literal

• With underscores for clarity

Multi-catch

略...

略...

都作一樣的事

Multi-catch

• It is a compile-time error if a disjunctive

type contains two alternatives Di, Dj where

Di is a subtype of Dj.

Multi-catch

• An exception parameter whose type is a

disjunctive type is implicitly considered to be final.

try { /* throws some ReflectiveOperationException */ }

catch (final ClassNotFoundException ex1) { /* body */ }

catch (final IllegalAccessException ex2) { /* body */ }

More precise rethrow

• JDK6...

...

...

// 作一些事

沒有宣告 Exception

More precise rethrow

• JDK7...

...

...

Inferring Types with <>

• 沒有 Generics 前

• 有了 Generics 後

• 有了 Inferring Types 後

Inferring Types with <>

• 僅使用 <> 表示推斷類型

• 不過別什麼都交給編譯器判斷....

Inferring Types with <>

• 如果...

• 推斷出來是 Integer 或 Number?

Inferring Types with <>

• 這有什麼問題?

Try-with-resources

• 讓這段程式碼更耐用一些...

Try-with-resources

• 讓這段程式碼更簡潔一些...

Try-with-resources

• 讓這段程式碼更簡潔一些...

Try-with-resources

try ResourceSpecification Block ⇒ { final VariableModifiers_minus_final R #resource = Expression; Throwable #primaryException = null; try ResourceSpecificationtail Block catch (Throwable #t) { #primaryException = t; throw #t; } finally { if (#resource != null) { if (#primaryException != null) { try { #resource.close(); } catch(Throwable #suppressedException) { #primaryException.addSuppressed(#suppressedException); } } else { #resource.close(); } } } }

Try-with-resources

• 如果要處理例外...

Try-with-resources

• 如果要處理例外... try-with-resources

Try-with-resources

• API 支援

– java.lang.AutoClosable

– java.io.Closeable 繼承 AutoCloseable

Try-with-resources

• API 支援 – java.beans.XMLDecoder

– java.beans.XMLEncoder

– java.io.Closeable

– java.io.ObjectInput

– java.io.ObjectOutput

– java.sql.Connection

– java.sql.ResultSet

– java.sql.Statement

– java.nio.channels.FileLock

– javax.sound.midi.MidiDevice

– javax.sound.midi.Receiver

– javax.sound.midi.Transmitter

– javax.sound.sampled.Line

Try-with-resources

• a 與 b 關閉的順序?

Heap pollution

• JDK6....

• OK...

要求編譯器檢查傳入引數是不是都是 T 型態

Heap pollution

• 希望編譯器檢查都是 List<String>....

• 編譯器提醒 doSome() 內部實作可能對每個引數,只當作 List ...

.....: warning: [unchecked] unchecked generic array creation of type java

.util.List<java.lang.String>[] for varargs parameter

Util.doSome(Arrays.asList("three", "four"), Arrays.asList(“five", “six"));

^

1 warning

Heap pollution

• 執行時期無法具體確認(reified)引數或變數型態

– http://en.wikipedia.org/wiki/Heap_pollution

• Java 的 Generics 是編譯時期檢查

• Generics 的物件相等性?

– http://caterpillar.onlyfun.net/JavaEssence/Gen

ericEquals.html

Simplified Varargs Method

Invocation

• JDK7...

....: warning: [unchecked] Possible heap pollution from parameterized var

arg type T

public static <T> List<T> doSome(T... t) {

^

where T is a type-variable:

T extends Object declared in method <T>doSome(T...)

1 warning

提醒設計 doSome() 保證不會發生 Heap Pollution

Simplified Varargs Method

Invocation

• @SuppressWarnings(“unchecked”)? – 連同其它的警訊也抑制了...

– 對 API 使用者也是有警訊...

• @SafeVarargs

• javac -Xlint:varargs;

Simplified Varargs Method

Invocation

• JDK7...

Unicode 6.0.0

• 2010-10-11 正式發佈

繪文字(emoji)

Unicode 6.0.0

• 2010-10-11 正式發佈

繪文字(emoji)

Unicode 6.0.0

• Java SE 7

– Unicode 5.1.0 Unicode 6.0.0

• Java Tutorial

– http://download.oracle.com/javase/tutorial/i18n/text/unicode.html

• Internationalization Enhancements in Java SE 7

– http://download.java.net/jdk7/docs/technotes/guides/intl/enhancements.7.html

JDBC 4.1

•繼承 AutoCloseable

– Connection

– ResultSet

– Statement

JDBC 4.1

JDBC 4.1

JDBC 4.1

• RowSetProvider

• RowSetFactory

java -Djavax.sql.rowset.RowSetFactory=com.sun.rowset.RowSetFactoryImpl

JSR203 / NIO.2

NIO

• java.nio

– Buffer

– Channel

– Selector

– Charset

NIO2

• File System API

• Channels API

– Updates to socket channel API

– Asynchronous I/O

File System API

• java.io.File 怎麼了?

– Not initially written to be extended

– Many of the methods without exceptions

– Methods behaved inconsistently across volumes and

file systems

– Methods for gaining simultaneous metadata about

files were inefficient

– Developers also requested the ability to develop their

own file system implementations, for examples, zip

files

– ...

File System API

• 新套件 – java.nio.file

– java.nio.file.attribute

• Java Tutorials: File I/O (Featuring NIO.2) – http://download.oracle.com/javase/tutorial/essential/io

/fileio.html

關於 Path

• Methods to access components

• Methods to test and compare

• Methods to combine paths

• File operations

• All methods that access file system throw IOException

• No other checked exceptions in API

關於 Path

• 建立 Path

•囉嗦點的話...

關於 Path • Path 操作

•實作 equals()

•實作 Iterable

同一階層

path.equals(otherPath)

Path path = ...;

for (Path name: path) {

System.out.println(name);

}

檔案移動與複製

• 支援選項設定

– copyTo(target, option...)

– moveTo(target, option...)

檔案屬性(Metadata)

• BasicFileAttributes

檔案屬性(Metadata)

• DosFileAttributes

• PosixFileAttributes

檔案屬性(Metadata)

• 設定群組、擁有者...

• 建立 Symbolic link、Hard link...

• 尋找 Link 的 Target...

檔案讀寫

• 針對 java.io 的 API

檔案讀寫 •針對 Channels 與 ByteBuffers

目錄讀取

• 使用 Glob 過濾目錄

• What is Glob

– http://download.oracle.com/javase/tutorial/essential/io

/fileOps.html#glob

FileVisitor

FileVisitor

啟始目錄

目錄 檔案 鏈結

檔案 檔案

visitFile

visitFile visitFile

visitFile

preVisitDirectory

preVisitDirectory postVisitDirectory

postVisitDirectory

監看目錄修改

• WatchService

新舊之間

• Legacy File I/O Code

– http://download.oracle.com/javase/tutorial/

essential/io/legacy.html

Asynchronous Channel API

• java.nio.channels

– AsynchronousSocketChannel

– AsynchronousServerSocketChannel

– AsynchronousFileChannel

– AsynchronousDatagramChannel

Asynchronous Channel API

• 建立AsychronousServerSocketChannel

–類似建立ServerSocketChannel並綁定位址

•接受連結

Asynchronous Channel API

• Future 模式

Asynchronous Channel API

• Future 模式

Asynchronous Channel API

• 客戶端建立AsynchronousSocketChannel

•開啟連結

Future<Void>

Asynchronous Channel API

• 客戶端傳送訊息

• 伺服端讀取訊息

JSR166y / Concurrency Updates

Concurrency Updates

• JDK5

– JSR 166: Concurrency Utilities

• JDK7

– JSR166y: Concurrency and collections updates

– java.util.concurrent

• ForkJoinPool

• Phaser

• TransferQueue

• ConcurrentLinkedDeque

• ThreadLocalRandom

• ...

Divide and conquer

Fork / Join 模式

• Divide and conquer 的一種實現策略

• 著重在如何切割任務與組合子任務結果

Fork / Join 框架

不需傳回值的子動作 透過泛型傳回值的子任務

Fork / Join 框架

• ForkJoinTask:類似執行緒的輕量級實體

• 有別於 ExecutorService 的 ForkJoinPool

– 採用 Work-stealing 演算,讓空閒的執行緒從執行較慢的執行緒中偷取任務

– 建構與處理器數量相當執行緒,減少頻繁切換負擔

Fibonacci

Fibonacci

結果 1134903170

耗時 24608

Fibonacci

Fibonacci

結果 1134903170

耗時 199604

Fibonacci

結果 1134903170

耗時 199604 .... you'd pick some minimum granularity

size for which you always sequentially

solve rather than subdividing.

搜尋檔案

搜尋檔案

結果 665

耗時 12813

搜尋檔案

搜尋檔案

結果 665

耗時 7596

JSR292 / Da Vinci Machine 專案

靜態定型語言

• 根據資料的型態資訊,將變數及運算式進行分類,型態資訊是在宣告變數上

• 在執行時期變數的型態資訊無法改變,資料只能被指定至同一種型態的變數

靜態定型語言

靜態定型語言

2: invokestatic #3 // Method doSome:(Ljava/lang/String;)Ljava/lang/Integer;

17: invokevirtual #7 // Method Other.doOther:(Ljava/lang/String;)Ljava/lang/Integer;

32: invokeinterface #9, 2 // InterfaceMethod Another.doAnother:(Ljava/lang/String;)Ljava/lang/Integer;

動態定型語言

• 型態資訊在資料本身而不是變數

• 變數本身的型態是在執行時期運算得知,也同一變數可以參考至各種型態的資料

function max(m, n) { if(n.lessThan(m)) {

return m;

}

return n;

}

def max(m, n):

return m if n.lessThan(m) else n

JavaScript

Python

動態定型語言的挑戰

• 參數與傳回值都沒有型態

• 執行時才提供型態資訊

• 無法提前得知呼叫的方法相關型態資訊

• 如何成功編譯為位元碼(Byte code)?

function max(m, n) {

if(n.lessThan(m)) {

return m;

}

return n;

}

動態定型語言的挑戰

• 為參數與傳回值建立合成(synthetic)類型

– 可符合位元碼對型態的要求

– 需要為各種語言建立特定實作(Implementer),以產生對應類型

– JVM 本身的類型(String、Integer...)通常也

無法直接對應

MyObject max(MyObject x, MyObject y) {

if(n.lessThan(m)) {

return n;

}

return m;

}

invokevirtual #9 // Method MyObject.lessThan:(Ljava/lang/MyObject;)Ljava/lang/Boolean;

動態定型語言的挑戰

• 運用反射呼叫(reflected invocation)

– java.lang.reflect.Method 提供某類別

或介面的方法直接呼叫(正是特定語言實作器所要求的)

–這些方法仍是執行時期從特定類別上取得

–執行時期的效能非常不彰

動態定型語言的挑戰

• 在 JVM 上執行特定語言直譯器(Interpreter)

– 非常非常....慢...

JSR 292

•為JVM與位元碼中新增invokedynamic指令

•新的方法連結機制

– java.lang.invoke

•CallSite

•MethodHandle

•...

invokedynamic <method-specification> <n>

• 考慮有個語言...

• 為這段程式碼產生位元碼...

a = 40;

b = a + 2;

bipush 40

istore_1

iload_1

invokestatic Method java/lang/Integer.valueOf:"(I)Ljava/lang/Integer;";

bipush 2

invokestatic Method java/lang/Integer.valueOf:"(I)Ljava/lang/Integer;";

invokedynamic InvokeDynamic

REF_invokeStatic:

Example.mybsm:

"(Ljava/lang/invoke/MethodHandles/Lookup;

Ljava/lang/String;

Ljava/lang/invoke/MethodType;)

Ljava/lang/invoke/CallSite;":

+:

"(Ljava/lang/Integer;

Ljava/lang/Integer;)

Ljava/lang/Integer;";

the invokedynamic call site is +

method implementation currently unknown

bootstrap method

JSR 292

• + 對整數的方法實作

• An invokedynamic call site is linked to a

method by means of a bootstrap method

類似 Reflection?

JSR 292

• java.lang.reflect.Method

– 非方法呼叫專用,執行時期有許多不必要資訊

– 重量級,速度慢

• java.lang.invoke.MethodHandle

–主要目的就是在方法呼叫

–輕量級,速度快

Recently rediscovered diagrams prove

Leonardo invented the first JVM?

. http://openjdk.java.net/projects/mlvm/

感謝 ● 林信良

● caterpillar@openhome.cc

● http://openhome.cc

Orz...