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.