前言

之前学习的过程中,每天都是老师说这个是JDK7以后可以使用,那个是JDK8以后可以使用,每天都记的很混乱,今天专门忙里偷闲,归拢整理下JDK7的新特性,对于JDK的新特性,后期会进行整理更新,希望可以帮助到有需要的朋友。

一,语法上

1.1switch中可以使用字串了

String s = "test";

switch (s) {

case "test" :

System.out.println("test");

case "test1" :

System.out.println("test1");

break ;

default :

System.out.println("break");

break ;

}

1.2二进制变量的表示,支持将整数类型用二进制来表示,用0b开头。

// 所有整数 int, short,long,byte都可以用二进制表示

// An 8-bit 'byte' value:

byte aByte = (byte) 0b00100001;

// A 16-bit 'short' value:

short aShort = (short) 0b1010000101000101;

// Some 32-bit 'int' values:

intanInt1 = 0b10100001010001011010000101000101;

intanInt2 = 0b101;

intanInt3 = 0B101; // The B can be upper or lower case.

// A 64-bit 'long' value. Note the "L" suffix:

long aLong =

0b1010000101000101101000010100010110100001010001011010000101000101L;

// 二进制在数组等的使用

final int[] phases = { 0b00110001, 0b01100010, 0b11000100, 0b10001001,0b00010011, 0b00100110, 0b01001100, 0b10011000 };

1.3 Try-with-resource语句

注意:实现java.lang.AutoCloseable接口的资源都可以放到try中,跟final里面的关闭资源类似; 按照声明逆序关闭资源 ;Try块抛出的异常通过Throwable.getSuppressed获取

try (java.util.zip.ZipFile zf = new java.util.zip.ZipFile(zipFileName);

java.io.BufferedWriter writer = java.nio.file.Files.newBufferedWriter(outputFilePath, charset)) {

// Enumerate each entry

for (java.util.Enumeration entries = zf.entries(); entries.hasMoreElements()) {

// Get the entry name and write it to the output file

String newLine = System.getProperty("line.separator");

String zipEntryName = ((java.util.zip.ZipEntry) entries

.nextElement()).getName() + newLine;

writer.write(zipEntryName, 0, zipEntryName.length());

}

}

}

1.4 Catch多个异常 说明:Catch异常类型为final; 生成Bytecode 会比多个catch小; Rethrow时保持异常类型

public static void main(String[] args) throws Exception {

try {

testthrows();

} catch (IOException | SQLException ex) {

throw ex;

}

}

public static void testthrows() throws IOException, SQLException {}

1.5 数字类型的下划线表示 更友好的表示方式,不过要注意下划线添加的一些标准,可以参考下面的示例

long creditCardNumber = 1234_5678_9012_3456L;

long socialSecurityNumber = 999_99_9999L;

float pi = 3.14_15F;

long hexBytes = 0xFF_EC_DE_5E;

long hexWords = 0xCAFE_BABE;

long maxLong = 0x7fff_ffff_ffff_ffffL;

byte nybbles = 0b0010_0101;

long bytes = 0b11010010_01101001_10010100_10010010;

//float pi1 = 3_.1415F;// Invalid; cannot put underscores adjacent to a decimal point

//float pi2 = 3._1415F;// Invalid; cannot put underscores adjacent to a decimal point

//long socialSecurityNumber1= 999_99_9999_L;// Invalid; cannot put underscores prior to an L suffix

//int x1 = _52;// This is an identifier, not a numeric literal

int x2 = 5_2;// OK (decimal literal)

//int x3 = 52_;// Invalid; cannot put underscores at the end of a literal

int x4 = 52;// OK (decimal literal)

//int x5 = 0_x52;// Invalid; cannot put underscores in the 0x radix prefix

//int x6 = 0x_52;// Invalid; cannot put underscores at the beginning of a number

int x7 = 0x5_2;// OK (hexadecimal literal)

//int x8 = 0x52_;// Invalid; cannot put underscores at the end of a number

int x9 = 0_52; // OK (octal literal)

int x10 = 05_2;// OK (octal literal)

//int x11 = 052_;// Invalid; cannot put underscores at the end of a number

1.6 泛型实例的创建可以通过类型推断来简化 可以去掉后面new部分的泛型类型,只用<>就可以了。

//使用泛型前

List strList = new ArrayList();

List strList4 = new ArrayList();

List>> strList5 = new ArrayList>>();

//编译器使用尖括号 (<>) 推断类型

List strList0 = new ArrayList();

List>> strList1 = new ArrayList>>();

List strList2 = new ArrayList<>();

List>> strList3 = new ArrayList<>();

List list = new ArrayList<>();

list.add("A");

// The following statement should fail since addAll expects

// Collection extends String>

//list.addAll(new ArrayList<>());

1.7在可变参数方法中传递非具体化参数,改进编译警告和错误

Heap pollution 指一个变量被指向另外一个不是相同类型的变量。例如

List l = new ArrayList();

List ls = l; // unchecked warning

l.add(0, new Integer(42)); // another unchecked warning

String s = ls.get(0); // ClassCastException is thrown

Jdk7:

public static void addToList (List listArg, T... elements) {

for (T x : elements) {

listArg.add(x);

}

}

你会得到一个warning

warning: [varargs] Possible heap pollution from parameterized vararg type

要消除警告,可以有三种方式

1.加 annotation @SafeVarargs

2.加 annotation @SuppressWarnings({"unchecked", "varargs"})

3.使用编译器参数 –Xlint:varargs;

1.8 信息更丰富的回溯追踪 就是上面try中try语句和里面的语句同时抛出异常时,异常栈的信息

java.io.IOException at Suppress.write(Suppress.java:19)at Suppress.main(Suppress.java:8)

Suppressed: java.io.IOException at Suppress.close(Suppress.java:24)

at Suppress.main(Suppress.java:9)

Suppressed: java.io.IOException at Suppress.close(Suppress.java:24)

at Suppress.main(Suppress.java:9)

二、NIO2的一些新特性

java.nio.file 和java.nio.file.attribute包 支持更详细属性,比如权限,所有者

symbolic and hard links支持

Path访问文件系统,Files支持各种文件操作

高效的访问metadata信息

递归查找文件树,文件扩展搜索

文件系统修改通知机制

File类操作API兼容

文件随机访问增强 mapping a region,locl a region,绝对位置读取

AIO Reactor(基于事件)和Proactor

下面列一些示例:

2.1 IO and New IO 监听文件系统变化通知

通过FileSystems.getDefault().newWatchService()获取watchService,然后将需要监听的path目录注册到这个watchservice中,对于这个目录的文件修改,新增,删除等实践可以配置,然后就自动能监听到响应的事件。

private WatchService watcher;

public TestWatcherService(Path path) throws IOException {

watcher = FileSystems.getDefault().newWatchService();

path.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);

}

public void handleEvents() throws InterruptedException {

while (true) {

WatchKey key = watcher.take();

for (WatchEvent> event : key.pollEvents()) {

WatchEvent.Kind kind = event.kind();

if (kind == OVERFLOW) {// 事件可能lost or discarded

continue;

}

WatchEvent e = (WatchEvent) event;

Path fileName = e.context();

System.out.printf("Event %s has happened,which fileName is %s%n",kind.name(), fileName);

}

if (!key.reset()) {

break;

}

2.2 IO and New IO遍历文件树,通过继承SimpleFileVisitor类,实现事件遍历目录树操作,然后通过Files.walkFileTree(listDir, opts,Integer.MAX_VALUE, walk);这个API来遍历目录树

private void workFilePath() {

Path listDir = Paths.get("/tmp"); // define the starting file

ListTree walk = new ListTree();

Files.walkFileTree(listDir, walk);

// 遍历的时候跟踪链接

EnumSet opts = EnumSet.of(FileVisitOption.FOLLOW_LINKS);

try {

Files.walkFileTree(listDir, opts, Integer.MAX_VALUE, walk);

} catch (IOException e) {

System.err.println(e);

}

class ListTree extends SimpleFileVisitor {// NIO2 递归遍历文件目录的接口

@Override

public FileVisitResult postVisitDirectory(Path dir, IOException exc) {

System.out.println("Visited directory: " + dir.toString());

return FileVisitResult.CONTINUE;

}

@Override

public FileVisitResult visitFileFailed(Path file, IOException exc) {

System.out.println(exc);

return FileVisitResult.CONTINUE;

}

}

2.3 AIO异步IO 文件和网络 异步IO在java

NIO2实现了,都是用AsynchronousFileChannel,AsynchronousSocketChanne等实现,关于同步阻塞IO,同步非阻塞IO,异步阻塞IO和异步非阻塞IO在ppt的这页上下面备注有说明,有兴趣的可以深入了解下。Java NIO2中就实现了操作系统的异步非阻塞IO。

// 使用AsynchronousFileChannel.open(path, withOptions(),taskExecutor))这个API对异步文件IO的处理

public static void asyFileChannel2() {

final int THREADS = 5;

ExecutorService taskExecutor = Executors.newFixedThreadPool(THREADS);

String encoding = System.getProperty("file.encoding");

List> list = new ArrayList<>();

int sheeps = 0;

Path path = Paths.get("/tmp","store.txt");

try (AsynchronousFileChannel asynchronousFileChannel = AsynchronousFileChannel.open(path, withOptions(), taskExecutor)) {

for (int i = 0; i < 50; i++) {

Callable worker = new Callable(){

@Override

public ByteBuffer call() throws Exception {

ByteBuffer buffer = ByteBuffer.allocateDirect(ThreadLocalRandom.current().nextInt(100, 200));

asynchronousFileChannel.read(buffer, ThreadLocalRandom)

……

三. JDBC 4.1

3.1.可以使用try-with-resources自动关闭Connection, ResultSet, 和 Statement资源对象

3.2. RowSet 1.1:引入RowSetFactory接口和RowSetProvider类,可以创建JDBC driver支持的各种 row sets,这里的rowset实现其实就是将sql语句上的一些操作转为方法的操作,封装了一些功能。

3.3. JDBC-ODBC驱动会在jdk8中删除

try (Statement stmt = con.createStatement()) {

RowSetFactory aFactory = RowSetProvider.newFactory();

CachedRowSet crs = aFactory.createCachedRowSet();

RowSetFactory rsf = RowSetProvider.newFactory("com.sun.rowset.RowSetFactoryImpl", null);

WebRowSet wrs = rsf.createWebRowSet();

createCachedRowSet

createFilteredRowSet

createJdbcRowSet

createJoinRowSet

createWebRowSet

}

四、并发工具增强

4.1.fork-join

最大的增强,充分利用多核特性,将大问题分解成各个子问题,由多个cpu可以同时解决多个子问题,最后合并结果,继承RecursiveTask,实现compute方法,然后调用fork计算,最后用join合并结果。

class Fibonacci extends RecursiveTask {

final int n;

Fibonacci(int n) {

this.n = n;

}

private int compute(int small) {

final int[] results = { 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 };

return results[small];

}

public Integer compute() {

if (n <= 10) {

return compute(n);

}

Fibonacci f1 = new Fibonacci(n - 1);

Fibonacci f2 = new Fibonacci(n - 2);

System.out.println("fork new thread for " + (n - 1));

f1.fork();

System.out.println("fork new thread for " + (n - 2));

f2.fork();

return f1.join() + f2.join();

}

}

4.2.ThreadLocalRandon 并发下随机数生成类,保证并发下的随机数生成的线程安全,实际上就是使用threadlocal

final int MAX = 100000;

ThreadLocalRandom threadLocalRandom = ThreadLocalRandom.current();

long start = System.nanoTime();

for (int i = 0; i < MAX; i++) {

threadLocalRandom.nextDouble();

}

long end = System.nanoTime() - start;

System.out.println("use time1 : " + end);

long start2 = System.nanoTime();

for (int i = 0; i < MAX; i++) {

Math.random();

}

long end2 = System.nanoTime() - start2;

System.out.println("use time2 : " + end2);

4.3. phaser 类似cyclebarrier和countdownlatch,不过可以动态添加资源减少资源

void runTasks(List tasks) {

final Phaser phaser = new Phaser(1); // "1" to register self

// create and start threads

for (final Runnable task : tasks) {

phaser.register();

new Thread() {

public void run() {

phaser.arriveAndAwaitAdvance(); // await all creation

task.run();

}

}.start();

}

// allow threads to start and deregister self

phaser.arriveAndDeregister();

}

结尾

由于个人能力问题,还有很多需要改进的地方,如有错误,烦请各位大佬私信或留言进行批评指正,在下定当及时更正!

java7 nio2 新特性_JDK7新特性,你知道几个?相关推荐

  1. Java13都要来了,你还不了解Java8的新(旧)特性?

    Java如今的版本迭代速度简直不要太快,一不留神,就错过了好几个版本了.官方版本虽然已经更新到Java12了,但是就目前来说,大多数Java系统还是运行在Java8上的,剩下一部分历史遗留系统还跑在J ...

  2. C++11新特性之新类型与初始化

    C++11新特性之新类型与初始化 snoone | 2016-06-23 11:57    浏览量(148)    评论(0)   推荐(0) 数据 这是C++11新特性介绍的第一部分,比较简单易懂, ...

  3. Android7.0新特性、新功能

    [本文转载来自http://blog.csdn.net/hao54216/article/details/52388755] 前言: 总想写点自己的东西,因为很多Android知识网上大部分都有教程, ...

  4. linux下软件发布,Linux Kernel 5.12发布下载,附新特性及新功能介绍

    Linus Torvalds在Linux内核邮件列表中宣布正式发布Linux Kernel 5.12版本,已提供linux-5.12.tar.xz/tar.gz下载,以下为你介绍该版本的更改.新特性及 ...

  5. html5 svg特性,HTML5新特性——HTML 5 Canvas vs. SVG

    Canvas 和 SVG 都允许您在浏览器中创建图形,但是它们在根本上是不同的. SVG SVG 是一种使用 XML 描述 2D 图形的语言. SVG 基于 XML,这意味着 SVG DOM 中的每个 ...

  6. Java8新特性之新时间API

    Java8新特性之新时间API 一.新时间API 1.1 之前时间API存在问题:线程安全问题.设计混乱 1.2 本地化日期时间API:LoaclDate.LocalTime.LocalDateTim ...

  7. linux5.5内核,Linux 5.5内核发布下载,附新功能及新特性介绍

    Linux Kernel 5.5内核已经正式发布了,提供linux-5.5.tar.xz下载,它具有许多更改和值得改进的地方,该内核版本也将在2020年晚些时候作为Ubuntu HWE堆栈的一部分反向 ...

  8. ES7新特性01-ES7新特性

    ES7新特性01-ES7新特性 文章目录 ES7新特性01-ES7新特性 includes **(幂运算) <!DOCTYPE html> <html lang="en&q ...

  9. ES10新特性01-ES10新特性

    ES10新特性01-ES10新特性 文章目录 ES10新特性01-ES10新特性 一.Object.fromEntries 二.字符串的扩展方法-trimStart 与 trimEnd 三.数组方法扩 ...

最新文章

  1. win10 anaconda 下pcl库的安装
  2. 如何正确配置Nginx+PHP
  3. 设计模式:选择排序(select sorting)
  4. 如何通过阅读英文网站提高英文水平
  5. java对接ldap_如何使用Java操作LDAP之LDAP连接(一)
  6. spark 常用函数介绍(python)
  7. ActiveX、OLE和COM介绍
  8. 数据中台精华问答 | 数据中台和传统数仓的区别是什么?
  9. java8 内存设置_Java 8内存分析
  10. IP地址基础和子网规划之其一
  11. MLT-type渲染算法review
  12. xadmin获取mysql_Django2集成xadmin详解-5-获取登录用户信息并填充相应Model字段
  13. IDEA 2018下载及破解
  14. FastDFS原理概括
  15. win10怎么做文件服务器,win10怎么做云服务器
  16. Win7 配置 Git 客户端 图文详解
  17. http 网络异常请求处理
  18. 咸鱼前端—CSS盒子模型
  19. 标准机构发布物联网安全测试指南
  20. bugku ctf 细心的大象 wirteup

热门文章

  1. 幼儿课外活动游戏_泰国清迈大小学校介绍 --【Little Star小星星幼儿园】
  2. java获取json中某个字段
  3. SpringMVC参数的传递——接收List数组类型的数据
  4. cheungssh mysql密码_CheungSSH安装及基本使用
  5. 属性的表示方法和对象的枚举
  6. Kafka Shell 基本操作
  7. MySQL 优化 —— EXPLAIN 执行计划详解
  8. Java常用设计模式————原型模式(二)之深拷贝与浅拷贝
  9. 微云服务器失败原因_梦幻西游:服务器发生异常?游戏出现明显卡顿感,正在排查问题...
  10. windows搭建tftp服务器_Ubuntu中搭建TFTP服务器