jdk 7&8 new features
7
Diamond Operator(菱形操作符)
You can omitted the type declaration of the right when working with Generics.
Map<String, List<Trade>> trades = new TreeMap<String, List<Trade>> ();
At now, case below is legal:
Map<String, List<Trade>> trades = new TreeMap <> ();
trades = new TreeMap() is legal, but it will make the compiler generaqte a couple of type-safety warnings.
Using strings in switch statements
Switch statements work either with primitive types or enumerated types. Java 7 introduced another type that we can use in Switch statements: the String type.
Automatic resource management
Java 7 has introduced another cool feature to manage the resources automatically. It is simple in operation, too. All we have to do is declare the resources in the try as follows:
try(resources_to_be_cleant){
// your code
}
There can be multiple statments in the () sperated by semicolumn(;).
Behind the scenes, the resources that should be auto closed must implement java.lang.AutoCloseable interface.The AutoCloseable is the parent of java.io.Closeable interface and has just one method close() that would be called by the JVM when the control comes out of the try block.
Numeric literals with underscores
Java 7 introduced underscores in identifying the places. For example, you can declare 1000 as shown below:
int thousand = 1_000;
Note that binary literals are also introduced in this release too.
Binary Literals with prefix “0b”
In JDK 7, you can express literal values in binary with prefix ‘0b’ (or ‘0B’) for integral types (byte, short, int and long), similar to C/C++ language. Before JDK 7, you can only use octal values (with prefix ‘0’) or hexadecimal values (with prefix ‘0x’ or ‘0X’).
int mask = 0b01010000101;
Improved exception handling
The multiple exceptions are caught in one catch block by using a ‘|’ operator. This way, you do not have to write dozens of exception catches. However, if you have bunch of exceptions that belong to different types, then you could use “multi multi-catch” blocks too.
try{
methodThatThrowsThreeExceptions();
} catch(ExceptionOne e) {
// log and deal with ExceptionOne
} catch(ExceptionTwo | ExceptionThree e) {
// log and deal with ExceptionTwo and ExceptionThree
}
New file System API(NIO 2.0)
Working with Path
A new java.nio.file package consists of classes and interfaces such as Path, Paths, FileSystem, FileSystems and others.
A Path is simply a reference to a file path. It is the equivalent (and with more features) to java.io.File.
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
The WatchService API lets you receive notification events upon changes to the subject( directory or file).
Steps involved in implementing the API are:
- Create a
WatchService. The service consists of a queue to holdWatchKeys. - Register the directory/file you wish to monitor with this
WatchService. - While registering, specify the types of events you wish to receive(create, modify or delete events).
- You need to start an infinite loop to listen to events.
- When an event occurs, a
WatchKeyis placed into the queue. - Consume the
WatchKeyand invoke queries on it.
Fork and Join
Java7 introduce a feature that work will be distributed across multiple cores and then joined togather to return the result set, which is called 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 breaakups. 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 specializzed implmentation of ExecutorService implementing the work-stealing algorithm. The ForkJoinTask handle the problems need to be solved. There are two implmentations of this class out of the box: the RecursiveAction and RecursiveTask. You can extend these classes and override the compute method. The only difference between between them is that the former one does not return a value while the latter returns an object of specified type. Finally, provide the ForkJoinTask to the Executor by calling invoke method on the ForkJoinPool.
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.
8
forEach() method in Iterable interface
Java 8 introduced forEach method in java.lang.Iterable interface so that while writing code we focus on business logic only. forEach method takes java.util.function.Consumer object as argument, so it helps in having our business logic at a sperate location that we can reuse.
myList.forEach(new Consumer<Integer>() {
public void accept(Integer t) {
System.out.println("forEach anonymous class Value::"+t);
}
});
default and static method in interfaces
In java8, we can use default and static keyword to create interfaces with method implementation. As to the Diamond Problem, the solution is that compiler will throw exception and we will have to provide implementation logic in the class implementing the interfaces.
菱形问题(diamond problem),就是说,当A的子类B和C同时实现了A中的方法,则同时继承了B和C的子类D在调用该方法时会出现混乱,无法得知该调用哪一个方法。
Functional Interfaces and Lambda Expressions
An interface with exactly one abstract method becomes Functional Interface. @FunctionalInterface annotation is optional. @FunctionalInterface annotation is a facility to avoid accidental addition of abstract methods in the functional interfaces.
One of the major benefits of functional interface is the possibility to use lambda expressions to instantiate them.
Java Stream API for Bulk Data Operations on Collections
A new java.util.stream has been added in Java8 to perform filter/map/reduce like operations with the collection. Stream API will allow sequential as well as parallel execution.
Collection interface has been extended with stream() and parallelStream() default methods to get the Stream for sequential and parallel execution.
Java Time API
java.time package in Java 8 will streamline the process of working with time in java. It has some sub-packages java.time.format that provides classes to print and parse dates and times and java.time.zone provides support for time-zones and their rules. The new Time API prefers enums over integer constants for months and days of the week. One of useful class is DateTimeFormatter for converting datetime objects to strings.
Collection API improvements
Beside forEach() method and Stream API for collections, there are other new methods:
- Iterator default method forEachRemaining(Consumer action) to perform the given action for each remaning element until all elements have been processed or the action throws an exception.
Collectiondefault methodremoveId(Predicate filter)to remove all of the elements of this collection that satisfy the given predicate.Collection spliterator()method returning Spliterator instance that can be used to traverse elements sequentially or parallel.- Map
repllaceAll(),compute(),merge()methods. - Performance Improvement for HashMap class with Key Collisions.
Concurrency API improvements
ConcurrentHashMapcompute(), forEach(), forEachEntry(), forEachKey(), forEachValue(), merge(), reduce() and search() methods.CompletableFuturethat may be explicitly completed(setting it’s value and status).- Executors newWorkStealingPool() method to create a work-stealing thread pool using all available processors as its target parallelism level.
Method References
Method reference can be used as a shorter and more readable alternative for a lambda expression which only calls an existing method. There are four varianrs of method references.
- Reference to s Static Method
The reference to a static method holds the following syntax:
ContainingClass::methodName
e.g:boolean isReal = list.stream().anyMatch(User::isRealUser);
- Reference to an Instance Method
The reference to an instance method holds the following syntax:
containingInstance::methodName
e.g:User user = new User();
boolean isLegalName = list.stream().antMatch(user::isLegalName);
- Reference to an Instance Method of an Object of a Particular Type
ContainingType::methodName
e.g:long count = list.stream().filter(String::isEmpty).count();
- Reference to a Contructor
ClassName::new
e.g:Stream<User> stream = list.stream().map(User::new);
Optional
Java 8 Optional class can help to handle situations where there is a possibility of getting the NullPointerException(NPE). It works as a container for the object of type T. It can return a value of this object if this value is not a null. When the value inside this container is null it allows doing some predefined actions instead of throwing NPE.
Creation of the Optional
- with its static methods
Optional<String> optional = Optional.empty();
- Returns an empty Optional
String str = "value";
Optional<String> optional = Optional.of(str);
- Returns an Optional which contains a non-null value
Optional<String> optional = Optional.ofNullable(getString());
Usage examples
List<String> listOpt = getList().orElseGet(() -> new ArrayList<>());
Optional<User> user = Optional.ofNullable(getUser());
String result = user
.map(User::getAddress)
.map(Address::getStreet)
.orElse("not specified");
We used the map() method to convert results of calling the getAddress() to the Optional
and getStreet() to Optional. If any of these methods returned null the map() would return an empty Optional.String value = null;
Optional<String> valueOpt = Optional.ofNullable(value);
String result = valueOpt.orElseThrow(CustomException::new).toUpperCase();
This usage change NPE with another exception.
Java IO improvements
- Files.list(Path dir) that returns a lazily populated Stream, the elements of which are the entries in the directory.
- Files.lines(Path path) that reads all lines from a file as a Stream.
- Files.find() that returns a Stream that is lazily populated with Path by searching for files in a file tree rooted at a given starting file.
- BufferedReader.lines() that return a Stream, the elements of which are lines read from this BufferedReader.
Miscellaneous Core API improvements
- ThreadLocal static method withInitial(Supplier supplier) to create instance easily.
- Comparator interface has been extended with a lot of default and static methods for natural ordering, reverse order etc.
- min(), max() and sum() methods in Integer, Long and Double wrapper classes.
- logicalAnd(), logicalOr() and logicalXor() methods in Boolean class.
- ZipFile.stream() method to get an ordered Stream over the ZIP file entries. Entries appear in the Stream in the order they appear in the central directory of the ZIP file.
- Serveral utility methods in Math class.
- jjs command is added to invoke Nashorn Engine.
- jdeps comomand is added to analyze class files.
- JDBC-ODBC Bridge has been removed.
- PermGen memory space has been removed.
others
Java 8 is introducing a completely new JVM JavaScript engine - Nashorn. This engine makes unique use of some of the new features introduced in Java 7 such as invokeDynamic to provide JVM-level speed to JavaScript Execution right there with the likes of V8 and SpiderMonkey.
jdk 7&8 new features的更多相关文章
- 你想了解的JDK 10版本更新都在这里
「MoreThanJava」 宣扬的是 「学习,不止 CODE」,本系列 Java 基础教程是自己在结合各方面的知识之后,对 Java 基础的一个总回顾,旨在 「帮助新朋友快速高质量的学习」. 当然 ...
- 搭建Android开发环境附图详解+模拟器安装(JDK+Eclipse+SDK+ADT)
——搭建android开发环境的方式有多种,比如:JDK+Eclipse+SDK+ADT或者JDK+Eclipse+捆绑好的AndroidSDK或者Android Studio. Google 决定将 ...
- Windows 搭建jdk、Tomcat、eclipse以及SVN、maven插件开发环境
未经允许,不得转载 Jdk1.7安装 jdk下载地址 http://www.oracle.com/technetwork/java/javase/downloads/index.html 安装jdk之 ...
- [转] - Configuring Android Studio: IDE & VM Options, JDK, etc
Configuring Android Studio: IDE & VM Options, JDK, etc You should not edit any files in the IDE ...
- How to Install JAVA 8 (JDK/JRE 8u111) on Debian 8 & 7 via PPA
Oracle JAVA 8 Stable release has been released on Mar,18 2014 and available to download and install. ...
- 使用JDK自带的visualvm进行性能监测和调优
使用JDK自带的visualvm进行性能监测和调优 1.关于VisualVm工具 VisualVM 提供在 Java 虚拟机 (Java Virutal Machine, JVM) 上运行的 J ...
- jdk+myeclipse配置安装相关步骤
1.JDK的安装JDK 版本:7u25 安装路径:c:\java(注意:装不装公共jre都可,自己可以选择安装到哪里)环境变量配置:(1)JAVA_HOME:C:\Java(就是你安装jdk的目录 ...
- windows JDK 版本切换
windows JDK 版本切换1. HKEY_LOCAL_MACHINE“SOFTWARE“JavaSoft“Java Runtime Environment“CurrentVersion, 把这个 ...
- Windows7 sp1 64位下安装配置eclipse+jdk+CDT+minGW
需要的工具: jdk-7u11-windows-x64.exe eclipse-SDK-4.2.2-win32-x86_64.zip cdt-master-8.1.2.zip mingw-get-i ...
随机推荐
- 模板 - 数据结构 - 可持久化无旋Treap/PersistentFHQTreap
有可能当树中有键值相同的节点时,貌似是要对Split和Merge均进行复制的,本人实测:只在Split的时候复制得到了一个WA,但只在Merge的时候复制还是AC,可能是恰好又躲过去了.有人说假如确保 ...
- 【洛谷】P1275 魔板(暴力&思维)
题目描述 有这样一种魔板:它是一个长方形的面板,被划分成n行m列的n*m个方格.每个方格内有一个小灯泡,灯泡的状态有两种(亮或暗).我们可以通过若干操作使魔板从一个状态改变为另一个状态.操作的方式有两 ...
- vue中全局filter和局部filter怎么用?
需求: 将价值上加上元单位符号(全局filter) <template> <div> 衣服价格:{{productPrice|formatTime}} </div> ...
- sem_init重复调用引发sem_wait线程无法被唤醒
问题 一段老代码,两个线程,一个线程调用sem_wait等待信号量,另外一个线程在某失败分支会调用sem_init清信号量,结果导致sem_wait线程无法被唤醒: 分析 Linux manpage ...
- im6q中的: pad csi
pad 管脚 pad control: 管脚控制 csi:CMOS serial interface, 即和CMOS摄像头的通信接口. imx 芯片的非常好的在线资料: https://www.dig ...
- 微信小程序丨将溢出的文本用省略号代替的方法
下面进入正题,有关于将溢出的文本用省略号代替的方法,不知道什么原因,我的程序用传统的代码无法解决: .text{ white-space: nowrap; overflow: hidden; text ...
- PHP课程环境安装总结文档
phpStudy的安装 1.找一个硬盘根目录,比如这里我使用E盘,在E盘根目录创建一个php的文件夹,进入php文件夹,如下图所示 2.在步骤1的php文件夹下再建立一个文件夹php_dev,如下图所 ...
- dubbo线程模型配置
首先了解一下dubbo线程模型 如果事件处理的逻辑能迅速完成,并且不会发起新的IO请求,比如只是在内存中记个标识.则直接在IO线程上处理更快,因为减少了线程池调度. 但如果事件处理逻辑较慢,或者需要发 ...
- Class as decorator in python
Class as decorator in python . https://www.geeksforgeeks.org/class-as-decorator-in-python/ http://co ...
- CRM 线索 客户 统称为 资源 客户服务管理篇 销售易
线索 客户 统称为 资源 - 国内版 Binghttps://cn.bing.com/search?FORM=U227DF&PC=U227&q=%E7%BA%BF%E7%B4%A2+% ...