java新特性

---恢复内容开始---

开发从java6到java7,再到java8;可网上一看,java9、java10 都已经出来了。不禁想问,怎么那么快!干了写什么!
那慢慢从头捋一捋试试(features and enhancements 特征和增强)

java6到java7

1.swing中

https://docs.oracle.com/javase/7/docs/technotes/guides/swing/enhancements-7.html
a.Jlayer Class:a flexible(灵活) and powerful decorator(装饰) for Swing components. It enables you to draw on components and respond to component events(响应容器事件) without modifying the underlying(底层) component directly.
b.Nimbus Look&Feel(L&F)(皮肤):moved from com.sun.java.swing to a standard API namespace, javax.swing
c.Heavyweight and Lightweight Components :mixing heavyweight (AWT 重量级) and lightweight (Swing) components in the same container is easy to accomplish in Java SE 7.
d.Shaped and Translucent(半透明) Windows:supports windows with transparency and non-rectangular shapes.
e.Hue-Saturation-Luminance (HSL) (色调、饱和度、亮度) Color Selection in JColorChooser Class:RT
other:AWT Enhancements、Drag n Drop Enhancements(拖拽事件涉及不受信任的应用时的安全问题)

2.IO and New IO(NIO) —— 自定义文件系统的非阻塞IO

A custom file system provider is useful in the following situations:
Developing a memory-based(基于内存) or zip-file-based file system
Developing a fault-tolerant distributed(容错) file system
Replacing or supplementing(补充) the default file system provider. The custom provider can augment(增加/扩充) the default provider by performing specific operations, such as logging all system operations, and delegate to the default provider for other routine(常规) operations.

a.File I/O (featuring NIO 2.0) in the Java Tutorials(教程); NIO stands for non-blocking I/O(非阻塞)
b.Developing a Custom File System Provider(自定义文件系统):The ava.nio.file.spi.FileSystemProvider class provides the ability to develop a custom file system provider that can be used to manage file system objects.
c.Zip File System Provider
others:
The directory <Java home>/sample/nio/chatserver/ contains samples that demonstrate(演示) the new APIs contained in the java.nio.file package
The directory <Java home>/demo/nio/zipfs/ contains samples that demonstrate the NIO.2 NFS (Network File System) file system
Prior(之前) to the JDK 7 release, direct buffers(直接缓冲区) allocated(分配) using java.nio.ByteBuffer.allocateDirect(int) were aligned on(对齐) a page boundary(边界). In JDK 7, the implementation has changed so that direct buffers are no longer page aligned(页面对齐). This should reduce the memory requirements of applications that create lots of small buffers.

3.NetWorking

The URLClassLoader.close method has been added. This method effectively eliminates(消除) the problem of how to support updated implementations of the classes and resources loaded from a particular codebase(代码库), and in particular(尤其是) from JAR files. See Closing a URLClassLoader for more information.
The Sockets Direct Protocol (SDP) provides access to high performance network connections; see Understanding the Sockets Direct Protocol in The Java Tutorial.

4.Security

a.Elliptic Curve Cryptography (ECC)(椭圆曲线加密): A new native provider has been added to the Java SE 7 release that provides several ECC-based algorithms(算法) (ECDSA/ECDH).
b.CertPath Algorithm Disabling: Weak cryptographic algorithms(弱加密算法) can now be disabled. For example, the MD2(Message Digest(摘要) 2) digest algorithm is no longer considered secure. The Java SE 7 release provides a mechanism(机制) for denying the use of specific algorithms in certification path(路径验证) processing and TLS handshaking(握手).
d.Connection-sensitive trust management(敏感连接的信任管理): Both trust managers and key managers now have the ability to examine parameters of the TLS connection, specifically the SSLSession under construction(正在构建的), during the handshake. For example, a trust manager might restrict(限制) the types of certificates used(使用的证书类型) based on the list of valid signature algorithms(根据有效前面算法).
e.Endpoint verification(验证): An endpoint identification algorithm can be specified to verify that a remote computer's host address matches its supplied certificate. Although this type of verification was previously performed for the HTTPS protocol (see HttpsURLConnection and HostnameVerifier), such verification can now be optionally(选择性地) performed at the TLS level.

5.Concurarency(并发) Utilities

a.The fork/join framework, which is based on the ForkJoinPool class, is an implementation of the Executor interface. It is designed to efficiently run a large number of tasks using a pool of worker threads(工作线程池). A work-stealing technique(工作窃取) is used to keep all the worker threads busy, to take full advantage of multiple processors. See Fork/Join in The Java Tutorials. The directory <Java home>/sample/forkjoin/ contains samples that demonstrate the fork/join framework.
b.The ThreadLocalRandom class eliminates contention(争用) among threads using pseudo-random numbers(伪随机数); see Concurrent Random Numbers.
c.The Phaser class is a new synchronization barrier(屏障同步), similar to CyclicBarrier.

20170716

 

1.switch中可以使用字串了

2.运用List<String> tempList = new ArrayList<>(); 即泛型实例化类型自动推断

3.语法上支持集合,而不一定是数组

4.新增一些取环境信息的工具方法

5.Boolean类型反转,空指针安全,参与位运算

6.两个char间的equals

7.安全的加减乘除

8.map集合支持并发请求,且可以写成 Map map = {name:"xxx",age:18};

 

 

 

1.lambda:也可称为闭包, 允许把函数作为一个方法的参数。Lambda 表达式免去了使用匿名方法的麻烦。

 lambda 表达式只能引用 final 或 final 局部变量,这就是说不能在 lambda 内部修改定义在域外的局部变量,否则会编译错误。

 Runnable r = ()-> System.out.println("hello lambda!");

 Comparator<Integer> cmp = (x, y) -> (x < y) ? -1 : ((x > y) ? 1 : 0);

 interface Action{ void run(String para);}

 public void execute(Action action){action,run();}

 execute((String s)->Ssytem.out.println(s)) —— SAM模式

 

2.在接口中,可以直接添加静态方法;在接口中,可以直接添加非抽象的实例方法,在实例方法的申明中,需要增加default关键字修饰,因此这种方法也称为默认方  法(防御方法),他是接口自带的方法。

 接口被实现后,实例可以直接使用这些默认方法,同时如果对默认方法需要重写时,可以直接重写即可。如下:

 public interface SourceInterface

 {

      int a = 5;

      int b = 10;

     public static int add()

      {

          return a + b;

      }

     public default int f1()

     {

         return a;

     }

}

 调用时:  SourceInterface.super.f1();  SourceInterface.add();

 

3.函数型接口(Functional): java.util.function

 一个lambda在运行时的表现是一个函数型接口(或者说是一个“SAM类型”),一种只拥有仅仅一个抽象方法的接口。

 所有的接口都标记上了@FunctionalInterface(http://download.java.net/jdk8/docs/api/java/lang/FunctionalInterface.html)运行时注解。

 除了它在运行时通过注解用javac去确认是否真的是一个功能型接口以外,它里面就不能有更多的抽象方法了(但可以有防御方法)。如:

 要想Java利用Groovy类型的迭代,我们就需要Collection和Iterable中都有一个新的方法。然而如果添加了这个方法,就将打破现有集合资源库的源代码级别的向后兼容性。因此,在Java 8中,java.util.Iterable 添加了forEach方法,并且为它提供了默认的实现。

 public interface Iterable<T> {

   Iterator iterator();

   public default void forEach(Consumer consumer) {

     for (T t : this) {

       consumer.accept(t);

      }

   }

 }

 添加新的默认方法并没有打破源码级别的兼容性,因为接口的实现类并不需要提供它们自己对于这个方法的实现。

 forEach方法利用了一个功能性接口作为参数,因而我们能够将一个lambda表达式作为一个参数传递进去。

 

4.方法引用使用一对冒号 :: ,通过方法的名字来指向一个方法。

 list.forEach(System.out::println);

 

5.Stream(流):Java中的Stream并不会存储元素,而是按需计算。

     Pipelining: 中间操作都会返回流对象本身。 这样多个操作可以串联成一个管道, 如同流式风格(fluent style)。 这样做可以对操作进行优化, 比如延迟执行(laziness)和短路( short-circuiting)。

    内部迭代: 以前对集合遍历都是通过Iterator或者For-Each的方式, 显式的在集合外部进行迭代, 这叫做外部迭代。 Stream提供了内部迭代的方式, 通过访问者模式(Visitor)实现

 parallelStream其实就是一个并行执行的流,它通过默认的ForkJoinPool,可能提高你的多线程任务的速度。

 Java8版本新增了很多新的方法,用于支持并行数组处理,如parallelSort():Arrays.parallelSort( arrayOfLong );

 统计:

 List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);

 IntSummaryStatistics stats = integers.stream().mapToInt((x) -> x).summaryStatistics();

 System.out.println("列表中最大的数 : " + stats.getMax());System.out.println("列表中最小的数 : " + stats.getMin());

 System.out.println("所有数之和 : " + stats.getSum()); System.out.println("平均数 : " + stats.getAverage());

 final Path path = new File( filename ).toPath();

try( Stream< String > lines = Files.lines( path, StandardCharsets.UTF_8 ) ) { lines.onClose( () -> System.out.println("Done!") ).forEach( System.out::println )}

 

 6.Optional 类是一个可以为null的容器对象。如果值存在则isPresent()方法会返回true,调用get()方法会返回该对象。

 它可以保存类型T的值,或者仅仅保存null,Optional 类的引入很好的解决空指针异常。

 void ifPresent(Consumer<? super T> consumer)  如果值存在则使用该值调用 consumer , 否则不做任何事情

 T orElse(T other)  如果存在该值,返回值, 否则返回 other。

 T orElseGet(Supplier<? extends T> other)  如果存在该值,返回值, 否则触发 other,并返回 other 调用的结果。

 <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier)  如果存在该值,返回包含的值,否则抛出由 Supplier 继承的异常

 

7.Java 8 Nashorn JavaScript

 Nashorn取代Rhino(JDK 1.6, JDK1.7)成为Java的嵌入式JavaScript引擎。带来了2到10倍的性能提升。

 使用 ScriptEngineManager, JavaScript 代码可以在 Java 中执行:

 import javax.script.ScriptEngineManager; import javax.script.ScriptEngine; import javax.script.ScriptException;

 public class Java8Tester{

 public static void main(String args[]){

 ScriptEngineManager scriptEngineManager = new ScriptEngineManager();

 ScriptEngine nashorn = scriptEngineManager.getEngineByName("nashorn");

 String name = "Runoob"; Integer result = null;

 try {

 nashorn.eval("print('" + name + "')");

 result = (Integer) nashorn.eval("10 + 2");

 }catch(ScriptException e){

 System.out.println("执行脚本错误: "+ e.getMessage());

 }

 System.out.println(result.toString());}}

 JavaScript中调用Java(需要使用 jjs 命令执行脚本?)

 var BigDecimal = Java.type('java.math.BigDecimal');

function calculate(amount, percentage) {

   var result = new BigDecimal(amount).multiply(

   new BigDecimal(percentage)).divide(new BigDecimal("100"), 2, BigDecimal.ROUND_HALF_EVEN);

   return result.toPlainString();

}

var result = calculate(568000000000000000023,13.9);

print(result);

 

8.新的Date-Time API java.time.*

 LocalDateTime now= LocalDateTime.now()

LocalDate date = LocalDate.of(2014, Month.DECEMBER, 12);

 LocalTime time = LocalTime.of(22, 15);

 final Duration duration = Duration.between( from, to ); //精确到纳秒

 

9.Base64

 Stringbase64encodedString = Base64.getEncoder().encodeToString("runoob?java8".getBytes("utf-8"));

byte[]base64decodedBytes = Base64.getDecoder().decode(base64encodedString);   

base64encodedString = Base64.getUrlEncoder().encodeToString("TutorialsPoint?java8".getBytes("utf-8"));

  byte[]mimeBytes = stringBuilder.toString().getBytes("utf-8");

 StringmimeEncodedString = Base64.getMimeEncoder().encodeToString(mimeBytes);

     基本:输出被映射到一组字符A-Za-z0-9+/,编码不添加任何行标,输出的解码仅支持A-Za-z0-9+/。

    URL:输出映射到一组字符A-Za-z0-9+_,输出是URL和文件。

    MIME:输出隐射到MIME友好格式。输出每行不超过76字符,并且使用'\r'并跟随'\n'作为分割。编码输出最后没有行分割。(MIME, 全称为“Multipurpose Internet Mail Extensions”, 比较确切的中文名称为“多用途互联网邮件扩展”。)

 

10.重复注解

 https://docs.oracle.com/javase/tutorial/java/annotations/repeating.html

 You can repeat an annotation anywhere

  @Repeatable(Schedules.class)

 public @interface Schedule {

 String dayOfMonth() default "first";

 String dayOfWeek() default "Mon";

 int hour() default 12;

 }

 

@Schedule(dayOfMonth="last")

 @Schedule(dayOfWeek="Fri", hour="23")

 public void doPeriodicCleanup() { ... }

 public @interface Schedules {

 Schedule[] value();

 }

 The value of the @Repeatable meta-annotation, in parentheses(圆括号), is the type of the container annotation that the Java compiler generates to store repeating annotations. In this example, the containing annotation type is Schedules, so repeating @Schedule annotations is stored in an @Schedules annotation.

 for( Schedule schedule: doPeriodicCleanup.class.getAnnotationsByType( Schedule.class ) ) { -----?

 }

 

11.使用Metaspace(JEP 122)代替持久代(PermGen space)。在JVM参数方面,使用-XX:MetaSpaceSize和-XX:MaxMetaspaceSize代替原来的-XX:PermSize和-XX:MaxPermSize。

 方法区:又叫静态区,跟堆一样,被所有的线程共享,主要用于存储已被虚拟机加载类的信息(Class)、常量池(final、static修饰)和即时编译器编译后的代码(方法数据、方法代码)等。方法区逻辑上属于堆的一部分,但是为了与堆进行区分,通常又叫“非堆”。

 PermGen(永久代)

 "java.lang.OutOfMemoryError: PermGen space "  方法区是 JVM 的规范,而PermGen space则是方法区的一种实现,只有 HotSpot 类型的虚拟机才有 “PermGen space”。由于方法区主要存储类的相关信息,所以对于动态生成类的情况比较容易出现永久代的内存溢出,比如jsp过多。

 Metaspace(元空间)

 其实,移除永久代的工作从JDK1.7就开始了。JDK1.7中,存储在永久代的部分数据就已经转移到了Java Heap或者是 Native Heap。但永久代仍存在于JDK1.7中,并没完全移除,譬如符号引用(Symbols)转移到了native heap;字面量(interned strings)转移到了java heap;类的静态变量(class statics)转移到了java heap。

 元空间的本质和永久代类似,都是对JVM规范中方法区的实现。不过元空间与永久代之间最大的区别在于:元空间并不在虚拟机中,而是使用本地内存。因此,默认情况下,元空间的大小仅受本地内存限制,但可以通过以下参数来指定元空间的大小:

   -XX:MetaspaceSize,初始空间大小,达到该值就会触发垃圾收集进行类型卸载,同时GC会对该值进行调整:如果释放了大量的空间,就适当降低该值;如果释放了很少的空间,那么在不超过MaxMetaspaceSize时,适当提高该值。

  -XX:MaxMetaspaceSize,最大空间,默认是没有限制的。

 除了上面两个指定大小的选项以外,还有两个与 GC 相关的属性:

  -XX:MinMetaspaceFreeRatio,在GC之后,最小的Metaspace剩余空间容量的百分比,减少为分配空间所导致的垃圾收集

  -XX:MaxMetaspaceFreeRatio,在GC之后,最大的Metaspace剩余空间容量的百分比,减少为释放空间所导致的垃圾收集

 

12. 类依赖分析器:jdeps

 jdeps可以展示包层级和类层级的Java类依赖关系,它以.class文件、目录或者Jar文件为输入,然后会把依赖关系输出到控制台。

jdeps org.springframework.core-3.0.5.RELEASE.jar

 依赖关系按照包分组,如果在classpath上找不到依赖,则显示”not found”.

 

13.并发性

 为java.util.concurrent.ConcurrentHashMap类添加了新的方法来支持聚焦操作;

 也为java.util.concurrentForkJoinPool类添加了新的方法来支持通用线程池操作;

 Java 8还添加了新的java.util.concurrent.locks.StampedLock类,用于支持基于容量的锁——该锁有三个模型用于支持读写操作(可以把这个锁当做是java.util.concurrent.locks.ReadWriteLock的替代者)。

 在java.util.concurrent.atomic包中也新增了不少工具类。

ConcurrentHashMap:Java1.8-ConcurrentHashMap

StampedLock

StampedLock是并发包里面jdk8版本新增的一个锁,该锁提供了三种模式的读写控制,三种模式分别如下:

  • 写锁writeLock,是个排它锁或者叫独占锁,同时只有一个线程可以获取该锁,当一个线程获取该锁后,其它请求的线程必须等待,当目前没有线程持有读锁或者写锁的时候才可以获取到该锁,请求该锁成功后会返回一个stamp票据变量用来表示该锁的版本,当释放该锁时候需要unlockWrite并传递参数stamp。
  • 悲观读锁readLock,是个共享锁,在没有线程获取独占写锁的情况下,同时多个线程可以获取该锁,如果已经有线程持有写锁,其他线程请求获取该读锁会被阻塞。这里讲的悲观其实是参考数据库中的乐观悲观锁的,这里说的悲观是说在具体操作数据前悲观的认为其他线程可能要对自己操作的数据进行修改,所以需要先对数据加锁,这是在读少写多的情况下的一种考虑,请求该锁成功后会返回一个stamp票据变量用来表示该锁的版本,当释放该锁时候需要unlockRead并传递参数stamp。
  • 乐观读锁tryOptimisticRead,是相对于悲观锁来说的,在操作数据前并没有通过CAS设置锁的状态,如果当前没有线程持有写锁,则简单的返回一个非0的stamp版本信息,获取该stamp后在具体操作数据前还需要调用validate验证下该stamp是否已经不可用,也就是看当调用tryOptimisticRead返回stamp后到到当前时间间是否有其他线程持有了写锁,如果是那么validate会返回0,否者就可以使用该stamp版本的锁对数据进行操作。由于tryOptimisticRead并没有使用CAS设置锁状态所以不需要显示的释放该锁。该锁的一个特点是适用于读多写少的场景,因为获取读锁只是使用与或操作进行检验,不涉及CAS操作,所以效率会高很多,但是同时由于没有使用真正的锁,在保证数据一致性上需要拷贝一份要操作的变量到方法栈,并且在操作数据时候可能其他写线程已经修改了数据,而我们操作的是方法栈里面的数据,也就是一个快照,所以最多返回的不是最新的数据,但是一致性还是得到保障的。

 

http://www.oracle.com/technetwork/java/javase/8-whats-new-2157071.html

https://www.oschina.net/translate/the-adventurous-developers-guide-to-jvm-languages?lang=chs&page=2#

 https://www.cnblogs.com/paddix/p/5309550.html

 http://blog.csdn.net/tieselingzhi/article/details/52815912

---恢复内容结束---

开发从java6到java7,再到java8;可网上一看,java9、java10 都已经出来了。不禁想问,怎么那么快!干了写什么!
那慢慢从头捋一捋试试(features and enhancements 特征和增强)


java6到java7

1.swing中

https://docs.oracle.com/javase/7/docs/technotes/guides/swing/enhancements-7.html
a.Jlayer Class:a flexible(灵活) and powerful decorator(装饰) for Swing components. It enables you to draw on components and respond to component events(响应容器事件) without modifying the underlying(底层) component directly.
b.Nimbus Look&Feel(L&F)(皮肤):moved from com.sun.java.swing to a standard API namespace, javax.swing
c.Heavyweight and Lightweight Components :mixing heavyweight (AWT 重量级) and lightweight (Swing) components in the same container is easy to accomplish in Java SE 7.
d.Shaped and Translucent(半透明) Windows:supports windows with transparency and non-rectangular shapes.
e.Hue-Saturation-Luminance (HSL) (色调、饱和度、亮度) Color Selection in JColorChooser Class:RT
other:AWT Enhancements、Drag n Drop Enhancements(拖拽事件涉及不受信任的应用时的安全问题)

2.IO and New IO(NIO) —— 自定义文件系统的非阻塞IO

A custom file system provider is useful in the following situations:
Developing a memory-based(基于内存) or zip-file-based file system
Developing a fault-tolerant distributed(容错) file system
Replacing or supplementing(补充) the default file system provider. The custom provider can augment(增加/扩充) the default provider by performing specific operations, such as logging all system operations, and delegate to the default provider for other routine(常规) operations.

a.File I/O (featuring NIO 2.0) in the Java Tutorials(教程); NIO stands for non-blocking I/O(非阻塞)
b.Developing a Custom File System Provider(自定义文件系统):The ava.nio.file.spi.FileSystemProvider class provides the ability to develop a custom file system provider that can be used to manage file system objects.
c.Zip File System Provider
others:
The directory <Java home>/sample/nio/chatserver/ contains samples that demonstrate(演示) the new APIs contained in the java.nio.file package
The directory <Java home>/demo/nio/zipfs/ contains samples that demonstrate the NIO.2 NFS (Network File System) file system
Prior(之前) to the JDK 7 release, direct buffers(直接缓冲区) allocated(分配) using java.nio.ByteBuffer.allocateDirect(int) were aligned on(对齐) a page boundary(边界). In JDK 7, the implementation has changed so that direct buffers are no longer page aligned(页面对齐). This should reduce the memory requirements of applications that create lots of small buffers.

3.NetWorking

The URLClassLoader.close method has been added. This method effectively eliminates(消除) the problem of how to support updated implementations of the classes and resources loaded from a particular codebase(代码库), and in particular(尤其是) from JAR files. See Closing a URLClassLoader for more information.
The Sockets Direct Protocol (SDP) provides access to high performance network connections; see Understanding the Sockets Direct Protocol in The Java Tutorial.

4.Security

 

 

 

 

 

 

 

1.switch中可以使用字串了

2.运用List<String> tempList = new ArrayList<>(); 即泛型实例化类型自动推断

3.语法上支持集合,而不一定是数组

4.新增一些取环境信息的工具方法

5.Boolean类型反转,空指针安全,参与位运算

6.两个char间的equals

7.安全的加减乘除

8.map集合支持并发请求,且可以写成 Map map = {name:"xxx",age:18};

 

 

 

 

 

1.lambda:也可称为闭包, 允许把函数作为一个方法的参数。Lambda 表达式免去了使用匿名方法的麻烦。

 lambda 表达式只能引用 final 或 final 局部变量,这就是说不能在 lambda 内部修改定义在域外的局部变量,否则会编译错误。

 Runnable r = ()-> System.out.println("hello lambda!");

 Comparator<Integer> cmp = (x, y) -> (x < y) ? -1 : ((x > y) ? 1 : 0);

 interface Action{ void run(String para);}

 public void execute(Action action){action,run();}

 execute((String s)->Ssytem.out.println(s)) —— SAM模式

 

2.在接口中,可以直接添加静态方法;在接口中,可以直接添加非抽象的实例方法,在实例方法的申明中,需要增加default关键字修饰,因此这种方法也称为默认方  法(防御方法),他是接口自带的方法。

 接口被实现后,实例可以直接使用这些默认方法,同时如果对默认方法需要重写时,可以直接重写即可。如下:

 public interface SourceInterface

 {

      int a = 5;

      int b = 10;

     public static int add()

      {

          return a + b;

      }

     public default int f1()

     {

         return a;

     }

}

 调用时:  SourceInterface.super.f1();  SourceInterface.add();

 

3.函数型接口(Functional): java.util.function

 一个lambda在运行时的表现是一个函数型接口(或者说是一个“SAM类型”),一种只拥有仅仅一个抽象方法的接口。

 所有的接口都标记上了@FunctionalInterface(http://download.java.net/jdk8/docs/api/java/lang/FunctionalInterface.html)运行时注解。

 除了它在运行时通过注解用javac去确认是否真的是一个功能型接口以外,它里面就不能有更多的抽象方法了(但可以有防御方法)。如:

 要想Java利用Groovy类型的迭代,我们就需要Collection和Iterable中都有一个新的方法。然而如果添加了这个方法,就将打破现有集合资源库的源代码级别的向后兼容性。因此,在Java 8中,java.util.Iterable 添加了forEach方法,并且为它提供了默认的实现。

 public interface Iterable<T> {

   Iterator iterator();

   public default void forEach(Consumer consumer) {

     for (T t : this) {

       consumer.accept(t);

      }

   }

 }

 添加新的默认方法并没有打破源码级别的兼容性,因为接口的实现类并不需要提供它们自己对于这个方法的实现。

 forEach方法利用了一个功能性接口作为参数,因而我们能够将一个lambda表达式作为一个参数传递进去。

 

4.方法引用使用一对冒号 :: ,通过方法的名字来指向一个方法。

 list.forEach(System.out::println);

 

5.Stream(流):Java中的Stream并不会存储元素,而是按需计算。

     Pipelining: 中间操作都会返回流对象本身。 这样多个操作可以串联成一个管道, 如同流式风格(fluent style)。 这样做可以对操作进行优化, 比如延迟执行(laziness)和短路( short-circuiting)。

    内部迭代: 以前对集合遍历都是通过Iterator或者For-Each的方式, 显式的在集合外部进行迭代, 这叫做外部迭代。 Stream提供了内部迭代的方式, 通过访问者模式(Visitor)实现

 parallelStream其实就是一个并行执行的流,它通过默认的ForkJoinPool,可能提高你的多线程任务的速度。

 Java8版本新增了很多新的方法,用于支持并行数组处理,如parallelSort():Arrays.parallelSort( arrayOfLong );

 统计:

 List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);

 IntSummaryStatistics stats = integers.stream().mapToInt((x) -> x).summaryStatistics();

 System.out.println("列表中最大的数 : " + stats.getMax());System.out.println("列表中最小的数 : " + stats.getMin());

 System.out.println("所有数之和 : " + stats.getSum()); System.out.println("平均数 : " + stats.getAverage());

 final Path path = new File( filename ).toPath();

try( Stream< String > lines = Files.lines( path, StandardCharsets.UTF_8 ) ) { lines.onClose( () -> System.out.println("Done!") ).forEach( System.out::println )}

 

 6.Optional 类是一个可以为null的容器对象。如果值存在则isPresent()方法会返回true,调用get()方法会返回该对象。

 它可以保存类型T的值,或者仅仅保存null,Optional 类的引入很好的解决空指针异常。

 void ifPresent(Consumer<? super T> consumer)  如果值存在则使用该值调用 consumer , 否则不做任何事情

 T orElse(T other)  如果存在该值,返回值, 否则返回 other。

 T orElseGet(Supplier<? extends T> other)  如果存在该值,返回值, 否则触发 other,并返回 other 调用的结果。

 <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier)  如果存在该值,返回包含的值,否则抛出由 Supplier 继承的异常

 

7.Java 8 Nashorn JavaScript

 Nashorn取代Rhino(JDK 1.6, JDK1.7)成为Java的嵌入式JavaScript引擎。带来了2到10倍的性能提升。

 使用 ScriptEngineManager, JavaScript 代码可以在 Java 中执行:

 import javax.script.ScriptEngineManager; import javax.script.ScriptEngine; import javax.script.ScriptException;

 public class Java8Tester{

 public static void main(String args[]){

 ScriptEngineManager scriptEngineManager = new ScriptEngineManager();

 ScriptEngine nashorn = scriptEngineManager.getEngineByName("nashorn");

 String name = "Runoob"; Integer result = null;

 try {

 nashorn.eval("print('" + name + "')");

 result = (Integer) nashorn.eval("10 + 2");

 }catch(ScriptException e){

 System.out.println("执行脚本错误: "+ e.getMessage());

 }

 System.out.println(result.toString());}}

 JavaScript中调用Java(需要使用 jjs 命令执行脚本?)

 var BigDecimal = Java.type('java.math.BigDecimal');

function calculate(amount, percentage) {

   var result = new BigDecimal(amount).multiply(

   new BigDecimal(percentage)).divide(new BigDecimal("100"), 2, BigDecimal.ROUND_HALF_EVEN);

   return result.toPlainString();

}

var result = calculate(568000000000000000023,13.9);

print(result);

 

8.新的Date-Time API java.time.*

 LocalDateTime now= LocalDateTime.now()

LocalDate date = LocalDate.of(2014, Month.DECEMBER, 12);

 LocalTime time = LocalTime.of(22, 15);

 final Duration duration = Duration.between( from, to ); //精确到纳秒

 

9.Base64

 Stringbase64encodedString = Base64.getEncoder().encodeToString("runoob?java8".getBytes("utf-8"));

byte[]base64decodedBytes = Base64.getDecoder().decode(base64encodedString);   

base64encodedString = Base64.getUrlEncoder().encodeToString("TutorialsPoint?java8".getBytes("utf-8"));

  byte[]mimeBytes = stringBuilder.toString().getBytes("utf-8");

 StringmimeEncodedString = Base64.getMimeEncoder().encodeToString(mimeBytes);

     基本:输出被映射到一组字符A-Za-z0-9+/,编码不添加任何行标,输出的解码仅支持A-Za-z0-9+/。

    URL:输出映射到一组字符A-Za-z0-9+_,输出是URL和文件。

    MIME:输出隐射到MIME友好格式。输出每行不超过76字符,并且使用'\r'并跟随'\n'作为分割。编码输出最后没有行分割。(MIME, 全称为“Multipurpose Internet Mail Extensions”, 比较确切的中文名称为“多用途互联网邮件扩展”。)

 

10.重复注解

 https://docs.oracle.com/javase/tutorial/java/annotations/repeating.html

 You can repeat an annotation anywhere

  @Repeatable(Schedules.class)

 public @interface Schedule {

 String dayOfMonth() default "first";

 String dayOfWeek() default "Mon";

 int hour() default 12;

 }

 

@Schedule(dayOfMonth="last")

 @Schedule(dayOfWeek="Fri", hour="23")

 public void doPeriodicCleanup() { ... }

 public @interface Schedules {

 Schedule[] value();

 }

 The value of the @Repeatable meta-annotation, in parentheses(圆括号), is the type of the container annotation that the Java compiler generates to store repeating annotations. In this example, the containing annotation type is Schedules, so repeating @Schedule annotations is stored in an @Schedules annotation.

 for( Schedule schedule: doPeriodicCleanup.class.getAnnotationsByType( Schedule.class ) ) { -----?

 }

 

11.使用Metaspace(JEP 122)代替持久代(PermGen space)。在JVM参数方面,使用-XX:MetaSpaceSize和-XX:MaxMetaspaceSize代替原来的-XX:PermSize和-XX:MaxPermSize。

 方法区:又叫静态区,跟堆一样,被所有的线程共享,主要用于存储已被虚拟机加载类的信息(Class)、常量池(final、static修饰)和即时编译器编译后的代码(方法数据、方法代码)等。方法区逻辑上属于堆的一部分,但是为了与堆进行区分,通常又叫“非堆”。

 PermGen(永久代)

 "java.lang.OutOfMemoryError: PermGen space "  方法区是 JVM 的规范,而PermGen space则是方法区的一种实现,只有 HotSpot 类型的虚拟机才有 “PermGen space”。由于方法区主要存储类的相关信息,所以对于动态生成类的情况比较容易出现永久代的内存溢出,比如jsp过多。

 Metaspace(元空间)

 其实,移除永久代的工作从JDK1.7就开始了。JDK1.7中,存储在永久代的部分数据就已经转移到了Java Heap或者是 Native Heap。但永久代仍存在于JDK1.7中,并没完全移除,譬如符号引用(Symbols)转移到了native heap;字面量(interned strings)转移到了java heap;类的静态变量(class statics)转移到了java heap。

 元空间的本质和永久代类似,都是对JVM规范中方法区的实现。不过元空间与永久代之间最大的区别在于:元空间并不在虚拟机中,而是使用本地内存。因此,默认情况下,元空间的大小仅受本地内存限制,但可以通过以下参数来指定元空间的大小:

   -XX:MetaspaceSize,初始空间大小,达到该值就会触发垃圾收集进行类型卸载,同时GC会对该值进行调整:如果释放了大量的空间,就适当降低该值;如果释放了很少的空间,那么在不超过MaxMetaspaceSize时,适当提高该值。

  -XX:MaxMetaspaceSize,最大空间,默认是没有限制的。

 除了上面两个指定大小的选项以外,还有两个与 GC 相关的属性:

  -XX:MinMetaspaceFreeRatio,在GC之后,最小的Metaspace剩余空间容量的百分比,减少为分配空间所导致的垃圾收集

  -XX:MaxMetaspaceFreeRatio,在GC之后,最大的Metaspace剩余空间容量的百分比,减少为释放空间所导致的垃圾收集

 

12. 类依赖分析器:jdeps

 jdeps可以展示包层级和类层级的Java类依赖关系,它以.class文件、目录或者Jar文件为输入,然后会把依赖关系输出到控制台。

jdeps org.springframework.core-3.0.5.RELEASE.jar

 依赖关系按照包分组,如果在classpath上找不到依赖,则显示”not found”.

 

13.并发性

 为java.util.concurrent.ConcurrentHashMap类添加了新的方法来支持聚焦操作;

 也为java.util.concurrentForkJoinPool类添加了新的方法来支持通用线程池操作;

 Java 8还添加了新的java.util.concurrent.locks.StampedLock类,用于支持基于容量的锁——该锁有三个模型用于支持读写操作(可以把这个锁当做是java.util.concurrent.locks.ReadWriteLock的替代者)。

 在java.util.concurrent.atomic包中也新增了不少工具类。

ConcurrentHashMap:Java1.8-ConcurrentHashMap

StampedLock

StampedLock是并发包里面jdk8版本新增的一个锁,该锁提供了三种模式的读写控制,三种模式分别如下:

  • 写锁writeLock,是个排它锁或者叫独占锁,同时只有一个线程可以获取该锁,当一个线程获取该锁后,其它请求的线程必须等待,当目前没有线程持有读锁或者写锁的时候才可以获取到该锁,请求该锁成功后会返回一个stamp票据变量用来表示该锁的版本,当释放该锁时候需要unlockWrite并传递参数stamp。
  • 悲观读锁readLock,是个共享锁,在没有线程获取独占写锁的情况下,同时多个线程可以获取该锁,如果已经有线程持有写锁,其他线程请求获取该读锁会被阻塞。这里讲的悲观其实是参考数据库中的乐观悲观锁的,这里说的悲观是说在具体操作数据前悲观的认为其他线程可能要对自己操作的数据进行修改,所以需要先对数据加锁,这是在读少写多的情况下的一种考虑,请求该锁成功后会返回一个stamp票据变量用来表示该锁的版本,当释放该锁时候需要unlockRead并传递参数stamp。
  • 乐观读锁tryOptimisticRead,是相对于悲观锁来说的,在操作数据前并没有通过CAS设置锁的状态,如果当前没有线程持有写锁,则简单的返回一个非0的stamp版本信息,获取该stamp后在具体操作数据前还需要调用validate验证下该stamp是否已经不可用,也就是看当调用tryOptimisticRead返回stamp后到到当前时间间是否有其他线程持有了写锁,如果是那么validate会返回0,否者就可以使用该stamp版本的锁对数据进行操作。由于tryOptimisticRead并没有使用CAS设置锁状态所以不需要显示的释放该锁。该锁的一个特点是适用于读多写少的场景,因为获取读锁只是使用与或操作进行检验,不涉及CAS操作,所以效率会高很多,但是同时由于没有使用真正的锁,在保证数据一致性上需要拷贝一份要操作的变量到方法栈,并且在操作数据时候可能其他写线程已经修改了数据,而我们操作的是方法栈里面的数据,也就是一个快照,所以最多返回的不是最新的数据,但是一致性还是得到保障的。

 

http://www.oracle.com/technetwork/java/javase/8-whats-new-2157071.html

https://www.oschina.net/translate/the-adventurous-developers-guide-to-jvm-languages?lang=chs&page=2#

 https://www.cnblogs.com/paddix/p/5309550.html

 http://blog.csdn.net/tieselingzhi/article/details/52815912

The fork/join framework, which is based on the ForkJoinPool class, is an implementation of the Executor interface. It is designed to efficiently run a large number of tasks using a pool of worker threads. A work-stealing technique is used to keep all the worker threads busy, to take full advantage of multiple processors. See Fork/Join in The Java Tutorials. The directory <Java home>/sample/forkjoin/ contains samples that demonstrate the fork/join framework.

The ThreadLocalRandom class eliminates contention among threads using pseudo-random numbers; see Concurrent Random Numbers.

The Phaser class is a new synchronization barrier, similar to CyclicBarrier.

posted @ 2018-03-02 11:16  wzbin  阅读(237)  评论(0编辑  收藏  举报