千呼萬喚始出來的java se 7

88
千千千千千千千千 千千千千千千千千 Java SE Java SE 7 7 千千千 [email protected] http://openhome.cc

Upload: javatwo2011

Post on 10-May-2015

3.711 views

Category:

Technology


1 download

DESCRIPTION

走過漫漫長路,Java SE 7 終於推出,帶來的東西不多也不少,閱讀 JSR 了解新功能總是無趣,選擇這一小時議程,快速體會 777(7 月 7 日 Java SE 7) 即將帶來的欣喜。

TRANSCRIPT

Page 1: 千呼萬喚始出來的Java SE 7

千呼萬喚始出來的千呼萬喚始出來的

Java SEJava SE 77千呼萬喚始出來的千呼萬喚始出來的

Java SEJava SE 77

● 林信良● [email protected]● http://openhome.cc

Page 2: 千呼萬喚始出來的Java SE 7

議程

• Java 進化史• JSR334 / Coin 專案• Unicode 6.0.0、JDBC 4.1

• JSR203 / NIO.2• JSR166y / Concurrency Updates

• JSR292 / Da Vinci Machine 專案

Page 3: 千呼萬喚始出來的Java SE 7

Java 進化史

2002/02/13 2004/09/29

2006/12/11

?2011/07/28

Page 4: 千呼萬喚始出來的Java SE 7

A / B 計畫• JDK 7 Features updated ! Plan B has

apparently been approved– http://www.baptiste-wicht.com/2010/09/jdk-7-f

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

Page 5: 千呼萬喚始出來的Java SE 7

JDK7 ...

Jigsawλλ

Language support for collections

Annotations on Java types

Page 6: 千呼萬喚始出來的Java SE 7

JDK7 有 ...• JDK 7 Features

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

NIO.2

Coin InvokeDynamic

ConcurrencyUpdates

Page 7: 千呼萬喚始出來的Java SE 7

JSR334 / Coin 專案

Page 8: 千呼萬喚始出來的Java SE 7

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

Page 9: 千呼萬喚始出來的Java SE 7

Strings in if-elseStrings in if-else

Page 10: 千呼萬喚始出來的Java SE 7

Strings in switchStrings in switch

Page 11: 千呼萬喚始出來的Java SE 7

反組譯 ...

先用 hashCode()

再用 equals()

Page 12: 千呼萬喚始出來的Java SE 7

Binary integral literals and Binary integral literals and underscores in numeric literalsunderscores in numeric literals

• Binary literal

• With underscores for clarity

Page 13: 千呼萬喚始出來的Java SE 7

Multi-catch

略 ...

略 ...

都作一樣的事

Page 14: 千呼萬喚始出來的Java SE 7

Multi-catch

• It is a compile-time error if a disjunctive type contains two alternatives Di, Dj where Di is a subtype of Dj.

Page 15: 千呼萬喚始出來的Java SE 7

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 */ }

Page 16: 千呼萬喚始出來的Java SE 7

More precise rethrow

• JDK6...

...

...

// 作一些事

沒有宣告 Exception

Page 17: 千呼萬喚始出來的Java SE 7

More precise rethrow

• JDK7...

...

...

Page 18: 千呼萬喚始出來的Java SE 7

Inferring Types with <>

• 沒有 Generics 前

• 有了 Generics 後

• 有了 Inferring Types 後

Page 19: 千呼萬喚始出來的Java SE 7

Inferring Types with <>

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

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

Page 20: 千呼萬喚始出來的Java SE 7

Inferring Types with <>

• 如果 ...

• 推斷出來是 Integer 或 Number ?

Page 21: 千呼萬喚始出來的Java SE 7

Inferring Types with <>• 這有什麼問題?

Page 22: 千呼萬喚始出來的Java SE 7

Try-with-resources

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

Page 23: 千呼萬喚始出來的Java SE 7

Try-with-resources

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

Page 24: 千呼萬喚始出來的Java SE 7

Try-with-resourcestry 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 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();      }    }  }}

Page 25: 千呼萬喚始出來的Java SE 7

Try-with-resources

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

Page 26: 千呼萬喚始出來的Java SE 7

Try-with-resources

• API 支援– java.lang.AutoClosable

– java.io.Closeable 繼承 AutoCloseable

Page 27: 千呼萬喚始出來的Java SE 7

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

Page 28: 千呼萬喚始出來的Java SE 7

Try-with-resources

• a 與 b 關閉的順序?

Page 29: 千呼萬喚始出來的Java SE 7

Heap pollution• JDK6....

• OK...

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

Page 30: 千呼萬喚始出來的Java SE 7

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

.....: 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

Page 31: 千呼萬喚始出來的Java SE 7

Heap pollution

• 執行時期無法具體確認( reified )引數或變數型態– http://en.wikipedia.org/wiki/Heap_pollution

• Java 的 Generics 是編譯時期檢查• Generics 的物件相等性?

– http://caterpillar.onlyfun.net/JavaEssence/GenericEquals.html

Page 32: 千呼萬喚始出來的Java SE 7

Simplified Varargs Method Simplified Varargs Method InvocationInvocation

• JDK7...

....: warning: [unchecked] Possible heap pollution from parameterized vararg 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

....: warning: [unchecked] Possible heap pollution from parameterized vararg 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

Page 33: 千呼萬喚始出來的Java SE 7

Simplified Varargs Method Simplified Varargs Method InvocationInvocation

• @SuppressWarnings(“unchecked”) ?– 連同其它的警訊也抑制了 ...– 對 API 使用者也是有警訊 ...

• @SafeVarargs

• javac -Xlint:varargs;

Page 34: 千呼萬喚始出來的Java SE 7

Simplified Varargs Method Simplified Varargs Method InvocationInvocation

• JDK7...

Page 35: 千呼萬喚始出來的Java SE 7

Unicode 6.0.0• 2010-10-11 正式發佈

繪文字( emoji )

Page 36: 千呼萬喚始出來的Java SE 7

Unicode 6.0.0

• Java SE 7– Unicode 5.1.0 Unicode 6.0.0

• Java Tutorial– http://download.oracle.com/javase/tutorial/i18

n/text/unicode.html

• Internationalization Enhancements in Java SE 7– http://download.java.net/jdk7/docs/technotes/

guides/intl/enhancements.7.html

Page 37: 千呼萬喚始出來的Java SE 7

JDBC 4.1

• 繼承 AutoCloseable – Connection– ResultSet– Statement

Page 38: 千呼萬喚始出來的Java SE 7

JDBC 4.1• RowSetProvider

• RowSetFactory

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

Page 39: 千呼萬喚始出來的Java SE 7

JSR203 / NIO.2

Page 40: 千呼萬喚始出來的Java SE 7

NIO

• java.nio– Buffer– Channel– Selector– Charset

NIO2• File System API

• Channels API– Updates to socket channel API– Asynchronous I/O

Page 41: 千呼萬喚始出來的Java SE 7

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

– ...

Page 42: 千呼萬喚始出來的Java SE 7

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

Page 43: 千呼萬喚始出來的Java SE 7

關於 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

Page 44: 千呼萬喚始出來的Java SE 7

關於 Path• 建立 Path

• 囉嗦點的話 ...

Page 45: 千呼萬喚始出來的Java SE 7

關於 Path• Path 操作

• 實作 equals()

• 實作 Iterable

同一階層

path.equals(otherPath)

Path path = ...; for (Path name: path) { System.out.println(name); }

Page 46: 千呼萬喚始出來的Java SE 7

檔案移動與複製• 支援選項設定

– copyTo(target, option...)– moveTo(target, option...)

Page 47: 千呼萬喚始出來的Java SE 7

檔案屬性( Metadata )• BasicFileAttributes

Page 48: 千呼萬喚始出來的Java SE 7

檔案屬性( Metadata )• DosFileAttributes

• PosixFileAttributes

Page 49: 千呼萬喚始出來的Java SE 7

檔案屬性( Metadata )• 設定群組、擁有者 ...• 建立 Symbolic link 、 Hard link...• 尋找 Link 的 Target...

Page 50: 千呼萬喚始出來的Java SE 7

檔案讀寫• 針對 java.io 的 API

Page 51: 千呼萬喚始出來的Java SE 7

檔案讀寫• 針對 Channels 與 ByteBuffers

Page 52: 千呼萬喚始出來的Java SE 7

目錄讀取• 使用 Glob 過濾目錄

• What is Glob– http://download.oracle.com/javase/tutorial/essential/io/

fileOps.html#glob

Page 53: 千呼萬喚始出來的Java SE 7

FileVisitor

Page 54: 千呼萬喚始出來的Java SE 7

FileVisitor

啟始目錄啟始目錄

目錄目錄檔案檔案 鏈結鏈結

檔案檔案 檔案檔案

visitFile

visitFile visitFile

visitFile

preVisitDirectory

preVisitDirectory postVisitDirectory

postVisitDirectory

Page 55: 千呼萬喚始出來的Java SE 7

監看目錄修改• WatchService

Page 56: 千呼萬喚始出來的Java SE 7

新舊之間• Legacy File I/O Code

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

Page 57: 千呼萬喚始出來的Java SE 7

Asynchronous Channel API

• java.nio.channels – AsynchronousSocketChannel – AsynchronousServerSocketChannel – AsynchronousFileChannel – AsynchronousDatagramChannel

Page 58: 千呼萬喚始出來的Java SE 7

Asynchronous Channel API

• 建立 AsychronousServerSocketChannel–類似建立 ServerSocketChannel 並綁定位

• 接受連結

Page 59: 千呼萬喚始出來的Java SE 7

Asynchronous Channel API• Future 模式

Page 60: 千呼萬喚始出來的Java SE 7

Asynchronous Channel API

• 客戶端建立 AsynchronousSocketChannel

• 開啟連結

Future<Void>

Page 61: 千呼萬喚始出來的Java SE 7

Asynchronous Channel API

• 客戶端傳送訊息

• 伺服端讀取訊息

Page 62: 千呼萬喚始出來的Java SE 7

Asynchronous Channel API

• The asynchronous channel APIs– http://www.ibm.com/developerworks/java/libra

ry/j-nio2-1/index.html

Page 63: 千呼萬喚始出來的Java SE 7

JSR166y / Concurrency Updates

Page 64: 千呼萬喚始出來的Java SE 7

Concurrency Updates

• JDK5– JSR 166: Concurrency Utilities

• JDK7– JSR166y: Concurrency and collections updates– java.util.concurrent

• ForkJoinPool• Phaser• TransferQueue• ConcurrentLinkedDeque• ThreadLocalRandom• ...

Page 65: 千呼萬喚始出來的Java SE 7

Divide and conquer

Page 66: 千呼萬喚始出來的Java SE 7

Fork / Join 模式• Divide and conquer 的一種實現策略• 著重在如何切割任務與組合子任務結果

Page 67: 千呼萬喚始出來的Java SE 7

Fork / Join 框架

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

Page 68: 千呼萬喚始出來的Java SE 7

Fork / Join 框架• ForkJoinTask :類似執行緒的輕量級實體• 有別於 ExecutorService 的 ForkJoinPool

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

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

Page 69: 千呼萬喚始出來的Java SE 7

Fibonacci

結果 1134903170耗時 24608

Page 70: 千呼萬喚始出來的Java SE 7

Fibonacci

結果 1134903170耗時 199604.... you'd pick some minimum granularity

size for which you always sequentially solve rather than subdividing.

.... you'd pick some minimum granularity size for which you always sequentially solve rather than subdividing.

Page 71: 千呼萬喚始出來的Java SE 7

搜尋檔案

結果 665耗時 12813

Page 72: 千呼萬喚始出來的Java SE 7

搜尋檔案

結果 665耗時 7596

Page 73: 千呼萬喚始出來的Java SE 7

JSR292 / Da Vinci Machine 專案

Page 74: 千呼萬喚始出來的Java SE 7

靜態定型語言• 根據資料的型態資訊,將變數及運算式進

行分類,型態資訊是在宣告變數上• 在執行時期變數的型態資訊無法改變,資

料只能被指定至同一種型態的變數

Page 75: 千呼萬喚始出來的Java SE 7

靜態定型語言

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;

Page 76: 千呼萬喚始出來的Java SE 7

動態定型語言• 型態資訊在資料本身而不是變數• 變數本身的型態是在執行時期運算得知,

也同一變數可以參考至各種型態的資料 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

Page 77: 千呼萬喚始出來的Java SE 7

動態定型語言的挑戰• 參數與傳回值都沒有型態• 執行時才提供型態資訊• 無法提前得知呼叫的方法相關型態資訊• 如何成功編譯為位元碼( Byte code )?

function max(m, n) { if(n.lessThan(m)) { return m; } return n;}

Page 78: 千呼萬喚始出來的Java SE 7

動態定型語言的挑戰•為參數與傳回值建立合成( 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;

Page 79: 千呼萬喚始出來的Java SE 7

動態定型語言的挑戰• 運用反射呼叫( reflected invocation )

– java.lang.reflect.Method 提供某類別或介面的方法直接呼叫(正是特定語言實作器所要求的)

–這些方法仍是執行時期從特定類別上取得–執行時期的效能非常不彰

Page 80: 千呼萬喚始出來的Java SE 7

動態定型語言的挑戰• 在 JVM 上執行特定語言直譯器( Interpreter

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

Page 81: 千呼萬喚始出來的Java SE 7

JSR 292

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

• 新的方法連結機制– java.lang.invoke

•CallSite•MethodHandle•...

invokedynamic <method-specification> <n> invokedynamic <method-specification> <n>

Page 82: 千呼萬喚始出來的Java SE 7

• 考慮有個語言 ...•為這段程式碼產生位元碼 ...

a = 40;b = a + 2; a = 40;b = a + 2;

bipush 40istore_1iload_1invokestatic Method java/lang/Integer.valueOf:"(I)Ljava/lang/Integer;";bipush 2invokestatic 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 + the invokedynamic call site is +

method implementation currently unknownmethod implementation currently unknown

bootstrap methodbootstrap method

Page 83: 千呼萬喚始出來的Java SE 7

JSR 292• + 對整數的方法實作

Page 84: 千呼萬喚始出來的Java SE 7

• An invokedynamic call site is linked to a method by means of a bootstrap method

類似 Reflection ?

Page 85: 千呼萬喚始出來的Java SE 7

JSR 292

• java.lang.reflect.Method– 非方法呼叫專用,執行時期有許多不必要資訊– 重量級,速度慢

• java.lang.invoke.MethodHandle–主要目的就是在方法呼叫–輕量級,速度快

Page 86: 千呼萬喚始出來的Java SE 7

JSR 292

• Java Virtual Machine Support for Non-Java Languages– http://download.java.net/jdk7/docs/technotes/

guides/vm/multiple-language-support.html

Page 87: 千呼萬喚始出來的Java SE 7

JSR 292

• If a programming language was a boat…– http://compsci.ca/blog/if-a-programming-langu

age-was-a-boat/

Page 88: 千呼萬喚始出來的Java SE 7

Recently rediscovered diagrams prove Leonardo invented the first JVM ?. http://openjdk.java.net/projects/mlvm/

感謝● 林信良● [email protected]● http://openhome.cc

Orz...