java7新特性
Diamond Operator “<>”
如果:
Map<String, List<Trade>> trades = new TreeMap<String, List<Trade>> ();
java7可以像下面這樣寫:
Map<String, List<Trade>> trades = new TreeMap <> ();
Using strings in switch statements
switch控制語句中增加字符串[String]支持,原來是原始類型[primitive types]和枚舉[enum];
public void processTrade(Trade t) {
String status = t.getStatus();
switch(status) {
caseNEW:
newTrade(t);
break;
caseEXECUTE:
executeTrade(t);
break;
default:
}
}
Automatic resource management
資源自動管理
java7 之前:
public voidoldTry() {
try{
fos= newFileOutputStream("movies.txt");
dos= newDataOutputStream(fos);
dos.writeUTF("Java 7 Block Buster");
} catch(IOException e) {
e.printStackTrace();
} finally{
try{
fos.close();
dos.close();
} catch(IOException e) {
// log the exception
}
}
}
java7開始:
public void newTry() {
try (FileOutputStream fos = new FileOutputStream("movies.txt");
DataOutputStream dos = new DataOutputStream(fos)) {
dos.writeUTF("Java 7 Block Buster");
} catch (IOException e) {
// log the exception
}
}
Numeric literals with underscores
增加了可閱讀性
java7之前 int num = 1000000000;
java7開始 int num = 1_000_000_000;
還可以這樣 int num = 1_2_3_4_5_6; 但首尾一定是數字。
Improved exception handling
java7前:
public void oldMultiCatch() {
try{
methodThatThrowsThreeExceptions();
} catch(ExceptionOne e) {
// log and deal with ExceptionOne
} catch(ExceptionTwo e) {
// log and deal with ExceptionTwo
} catch(ExceptionThree e) {
// log and deal with ExceptionThree
}
}
java7開始:
public void newMultiCatch() {
try{
methodThatThrowsThreeExceptions();
} catch(ExceptionOne | ExceptionTwo | ExceptionThree e) {
// log and deal with all Exceptions
}
}
New file system API (NIO 2.0)
he NIO 2.0 has come forward with many enhancements. It’s also introduced new classes to ease the life of a developer when working with multiple file systems.
對多文件系統中開發更輕鬆
Working with Path
新增一個操作文件系統的包
A new java.nio.file package consists of classes and interfaces such as Path, Paths, FileSystem, FileSystems and others.
Path
等同於File
但具有更多的功能
Path path= Paths.get("c:\\Temp\\temp\\test.txt");
System.out.println("Number of Nodes:"+ path.getNameCount());
System.out.println("File Name:"+ path.getFileName());
System.out.println("File Root:"+ path.getRoot());
System.out.println("File Parent:"+ path.getParent());
控制檯輸出:
Number of Nodes:3
File Name:test.txt
File Root:c:\
File Parent:c:\Temp\temp
The Files class exposes two delete methods, one that throws NoSuchFileException and the other that does not.
The following delete method invocation throws NoSuchFileException, so you have to handle it:
Files.delete(path);
Where as Files.deleteIfExists(path) does not throw exception (as expected) if the file/directory does not exist.
You can use other utility methods such as Files.copy(..) and Files.move(..) to act on a file system efficiently. Similarly, use the createSymbolicLink(..) method to create symbolic links using your code.
File change notifications
文件變化通知
private WatchService watchService;
private void init() {
Path path= Paths.get("C:\\Temp\\temp\\");
try{
watchService= FileSystems.getDefault().newWatchService();
path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);
} catch(IOException e) {
System.out.println("IOException"+ e.getMessage());
}
}
/**
* The police will start making rounds
*/
private void doRounds() {
WatchKey key = null;
while(true) {
try{
key = watchService.take();
for(WatchEvent<?> event : key.pollEvents()) {
WatchEvent.Kind<?> kind = event.kind();
System.out.println("Event on "+ event.context().toString() + " is " + kind);
}
} catch(InterruptedException e) {
System.out.println("InterruptedException: "+e.getMessage());
}
boolean reset = key.reset();
if(!reset)
break;
}
}
Fork and Join
將一個任務給cpu的多個核心去處理
The effective use of parallel cores in a Java program has always been a challenge. There were few home-grown frameworks that would distribute the work across multiple cores and then join them to return the result set. Java 7 has incorporated this feature as a Fork and Join framework.
Basically the Fork-Join breaks the task at hand into mini-tasks until the mini-task is simple enough that it can be solved without further breakups. It’s like a divide-and-conquer algorithm. One important concept to note in this framework is that ideally no worker thread is idle. They implement a work-stealing algorithm in that idle workers “steal” the work from those workers who are busy.
The core classes supporting the Fork-Join mechanism are ForkJoinPool and ForkJoinTask. The ForkJoinPool is basically a specialized implementation of ExecutorService implementing the work-stealing algorithm we talked about above.
We create an instance of ForkJoinPool by providing the target parallelism level — the number of processors as shown below:
ForkJoinPool pool = new ForkJoinPool(numberOfProcessors)
Where numberOfProcessors = Runtime.getRunTime().availableProcessors();
However, the default ForkJoinPool instantiation would set the parallelism level equal to the same number obtained as above.
The problem that needs to be solved is coded in a ForkJoinTask. However, there are two implementations of this class out of the box: the RecursiveAction and RecursiveTask. The only difference between these two classes is that the former one does not return a value while the latter returns an object of specified type.
Here’s how to create a RecursiveAction or RecursiveTask class that represents your requirement problem (I use the RecursiveAction class):
public class MyBigProblemTask extends RecursiveAction {
@Override
protected void compute() {
. . . // your problem invocation goes here
}
}
You have to override the compute method where in you need to provide the computing functionality. Now, provide this ForkJoinTask to the Executor by calling invoke method on the ForkJoinPool:
pool.invoke(task);
Supporting dynamism
支持動態語言
In Java 7, a new feature called invokedynamic was introduced. This makes VM changes to incorporate non-Java language requirements. A new package, java.lang.invoke, consisting of classes such as MethodHandle, CallSite and others, has been created to extend the support of dynamic languages.