JDK7新特性,你知道几个

1.1switch中可以使用字串了

[plain] view plaincopy

  1. String s = "test";
  2. switch (s) {
  3. case "test" :
  4. System.out.println("test");
  5. case "test1" :
  6. System.out.println("test1");
  7. break ;
  8. default :
  9. System.out.println("break");
  10. break ;
  11. }

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

[plain] view plaincopy

  1. // 所有整数 int, short,long,byte都可以用二进制表示
  2. // An 8-bit 'byte' value:
  3. byte aByte = (byte) 0b00100001;
  4. // A 16-bit 'short' value:
  5. short aShort = (short) 0b1010000101000101;
  6. // Some 32-bit 'int' values:
  7. intanInt1 = 0b10100001010001011010000101000101;
  8. intanInt2 = 0b101;
  9. intanInt3 = 0B101; // The B can be upper or lower case.
  10. // A 64-bit 'long' value. Note the "L" suffix:
  11. long aLong =
  12. 0b1010000101000101101000010100010110100001010001011010000101000101L;
  13. // 二进制在数组等的使用
  14. final int[] phases = { 0b00110001, 0b01100010, 0b11000100, 0b10001001,0b00010011, 0b00100110, 0b01001100, 0b10011000 };

1.3 Try-with-resource语句

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

[plain] view plaincopy

  1. try (java.util.zip.ZipFile zf = new java.util.zip.ZipFile(zipFileName);
  2. java.io.BufferedWriter writer = java.nio.file.Files.newBufferedWriter(outputFilePath, charset)) {
  3. // Enumerate each entry
  4. for (java.util.Enumeration entries = zf.entries(); entries.hasMoreElements()) {
  5. // Get the entry name and write it to the output file
  6. String newLine = System.getProperty("line.separator");
  7. String zipEntryName = ((java.util.zip.ZipEntry) entries
  8. .nextElement()).getName() + newLine;
  9. writer.write(zipEntryName, 0, zipEntryName.length());
  10. }
  11. }
  12. }

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

[plain] view plaincopy

  1. public static void main(String[] args) throws Exception {
  2. try {
  3. testthrows();
  4. } catch (IOException | SQLException ex) {
  5. throw ex;
  6. }
  7. }
  8. public static void testthrows() throws IOException, SQLException {}

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

[plain] view plaincopy

  1. long creditCardNumber = 1234_5678_9012_3456L;
  2. long socialSecurityNumber = 999_99_9999L;
  3. float pi = 3.14_15F;
  4. long hexBytes = 0xFF_EC_DE_5E;
  5. long hexWords = 0xCAFE_BABE;
  6. long maxLong = 0x7fff_ffff_ffff_ffffL;
  7. byte nybbles = 0b0010_0101;
  8. long bytes = 0b11010010_01101001_10010100_10010010;
  9. //float pi1 = 3_.1415F;// Invalid; cannot put underscores adjacent to a decimal point
  10. //float pi2 = 3._1415F;// Invalid; cannot put underscores adjacent to a decimal point
  11. //long socialSecurityNumber1= 999_99_9999_L;// Invalid; cannot put underscores prior to an L suffix
  12. //int x1 = _52;// This is an identifier, not a numeric literal
  13. int x2 = 5_2;// OK (decimal literal)
  14. //int x3 = 52_;// Invalid; cannot put underscores at the end of a literal
  15. int x4 = 52;// OK (decimal literal)
  16. //int x5 = 0_x52;// Invalid; cannot put underscores in the 0x radix prefix
  17. //int x6 = 0x_52;// Invalid; cannot put underscores at the beginning of a number
  18. int x7 = 0x5_2;// OK (hexadecimal literal)
  19. //int x8 = 0x52_;// Invalid; cannot put underscores at the end of a number
  20. int x9 = 0_52; // OK (octal literal)
  21. int x10 = 05_2;// OK (octal literal)
  22. //int x11 = 052_;// Invalid; cannot put underscores at the end of a number

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

[plain] view plaincopy

  1. //使用泛型前
  2. List strList = new ArrayList();
  3. List<String> strList4 = new ArrayList<String>();
  4. List<Map<String, List<String>>> strList5 =  new ArrayList<Map<String, List<String>>>();
  5. //编译器使用尖括号 (<>) 推断类型
  6. List<String> strList0 = new ArrayList<String>();
  7. List<Map<String, List<String>>> strList1 =  new ArrayList<Map<String, List<String>>>();
  8. List<String> strList2 = new ArrayList<>();
  9. List<Map<String, List<String>>> strList3 = new ArrayList<>();
  10. List<String> list = new ArrayList<>();
  11. list.add("A");
  12. // The following statement should fail since addAll expects
  13. // Collection<? extends String>
  14. //list.addAll(new ArrayList<>());

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

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

[plain] view plaincopy

  1. List l = new ArrayList<Number>();
  2. List<String> ls = l;       // unchecked warning
  3. l.add(0, new Integer(42)); // another unchecked warning
  4. String s = ls.get(0); // ClassCastException is thrown
  5. Jdk7:
  6. public static <T> void addToList (List<T> listArg, T... elements) {
  7. for (T x : elements) {
  8. listArg.add(x);
  9. }
  10. }
  11. 你会得到一个warning
  12. warning: [varargs] Possible heap pollution from parameterized vararg type
  13. 要消除警告,可以有三种方式
  14. 1.加 annotation @SafeVarargs
  15. 2.加 annotation @SuppressWarnings({"unchecked", "varargs"})
  16. 3.使用编译器参数 –Xlint:varargs;

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

[plain] view plaincopy

  1. java.io.IOException at Suppress.write(Suppress.java:19)at Suppress.main(Suppress.java:8)
  2. Suppressed:  java.io.IOException at Suppress.close(Suppress.java:24)
  3. at Suppress.main(Suppress.java:9)
  4. Suppressed:  java.io.IOException at  Suppress.close(Suppress.java:24)
  5. at  Suppress.main(Suppress.java:9)

二、NIO2的一些新特性

  1. java.nio.file 和java.nio.file.attribute包 支持更详细属性,比如权限,所有者
  2. symbolic and hard links支持
  3. Path访问文件系统,Files支持各种文件操作
  4. 高效的访问metadata信息
  5. 递归查找文件树,文件扩展搜索
  6. 文件系统修改通知机制
  7. File类操作API兼容
  8. 文件随机访问增强 mapping a region,locl a region,绝对位置读取
  9. AIO Reactor(基于事件)和Proactor
    下面列一些示例:

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

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

    [plain] view plaincopy

    1. private WatchService watcher;
    2. public TestWatcherService(Path path) throws IOException {
    3. watcher = FileSystems.getDefault().newWatchService();
    4. path.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
    5. }
    6. public void handleEvents() throws InterruptedException {
    7. while (true) {
    8. WatchKey key = watcher.take();
    9. for (WatchEvent<?> event : key.pollEvents()) {
    10. WatchEvent.Kind kind = event.kind();
    11. if (kind == OVERFLOW) {// 事件可能lost or discarded
    12. continue;
    13. }
    14. WatchEvent<Path> e = (WatchEvent<Path>) event;
    15. Path fileName = e.context();
    16. System.out.printf("Event %s has happened,which fileName is %s%n",kind.name(), fileName);
    17. }
    18. if (!key.reset()) {
    19. break;
    20. }

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

    [plain] view plaincopy

    1. private void workFilePath() {
    2. Path listDir = Paths.get("/tmp"); // define the starting file
    3. ListTree walk = new ListTree();
    4. Files.walkFileTree(listDir, walk);
    5. // 遍历的时候跟踪链接
    6. EnumSet opts = EnumSet.of(FileVisitOption.FOLLOW_LINKS);
    7. try {
    8. Files.walkFileTree(listDir, opts, Integer.MAX_VALUE, walk);
    9. } catch (IOException e) {
    10. System.err.println(e);
    11. }
    12. class ListTree extends SimpleFileVisitor<Path> {// NIO2 递归遍历文件目录的接口
    13. @Override
    14. public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
    15. System.out.println("Visited directory: " + dir.toString());
    16. return FileVisitResult.CONTINUE;
    17. }
    18. @Override
    19. public FileVisitResult visitFileFailed(Path file, IOException exc) {
    20. System.out.println(exc);
    21. return FileVisitResult.CONTINUE;
    22. }
    23. }

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

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

    [plain] view plaincopy

    1. // 使用AsynchronousFileChannel.open(path, withOptions(),taskExecutor))这个API对异步文件IO的处理
    2. public static void asyFileChannel2() {
    3. final int THREADS = 5;
    4. ExecutorService taskExecutor = Executors.newFixedThreadPool(THREADS);
    5. String encoding = System.getProperty("file.encoding");
    6. List<Future<ByteBuffer>> list = new ArrayList<>();
    7. int sheeps = 0;
    8. Path path = Paths.get("/tmp","store.txt");
    9. try (AsynchronousFileChannel asynchronousFileChannel = AsynchronousFileChannel.open(path, withOptions(), taskExecutor)) {
    10. for (int i = 0; i < 50; i++) {
    11. Callable<ByteBuffer> worker = new Callable<ByteBuffer>(){
    12. @Override
    13. public ByteBuffer call() throws Exception {
    14. ByteBuffer buffer = ByteBuffer.allocateDirect(ThreadLocalRandom.current().nextInt(100, 200));
    15. asynchronousFileChannel.read(buffer, ThreadLocalRandom)
    16. ……

    三. 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中删除

[plain] view plaincopy

  1. try (Statement stmt = con.createStatement()) {
  2. RowSetFactory aFactory = RowSetProvider.newFactory();
  3. CachedRowSet crs = aFactory.createCachedRowSet();
  4. RowSetFactory rsf = RowSetProvider.newFactory("com.sun.rowset.RowSetFactoryImpl", null);
  5. WebRowSet wrs = rsf.createWebRowSet();
  6. createCachedRowSet
  7. createFilteredRowSet
  8. createJdbcRowSet
  9. createJoinRowSet
  10. createWebRowSet
  11. }

四、并发工具增强

4.1.fork-join

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

[plain] view plaincopy

  1. class Fibonacci extends RecursiveTask<Integer> {
  2. final int n;
  3. Fibonacci(int n) {
  4. this.n = n;
  5. }
  6. private int compute(int small) {
  7. final int[] results = { 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 };
  8. return results[small];
  9. }
  10. public Integer compute() {
  11. if (n <= 10) {
  12. return compute(n);
  13. }
  14. Fibonacci f1 = new Fibonacci(n - 1);
  15. Fibonacci f2 = new Fibonacci(n - 2);
  16. System.out.println("fork new thread for " + (n - 1));
  17. f1.fork();
  18. System.out.println("fork new thread for " + (n - 2));
  19. f2.fork();
  20. return f1.join() + f2.join();
  21. }
  22. }

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

[plain] view plaincopy

  1. final int MAX = 100000;
  2. ThreadLocalRandom threadLocalRandom = ThreadLocalRandom.current();
  3. long start = System.nanoTime();
  4. for (int i = 0; i < MAX; i++) {
  5. threadLocalRandom.nextDouble();
  6. }
  7. long end = System.nanoTime() - start;
  8. System.out.println("use time1 : " + end);
  9. long start2 = System.nanoTime();
  10. for (int i = 0; i < MAX; i++) {
  11. Math.random();
  12. }
  13. long end2 = System.nanoTime() - start2;
  14. System.out.println("use time2 : " + end2);

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

[plain] view plaincopy

  1. void runTasks(List<Runnable> tasks) {
  2. final Phaser phaser = new Phaser(1); // "1" to register self
  3. // create and start threads
  4. for (final Runnable task : tasks) {
  5. phaser.register();
  6. new Thread() {
  7. public void run() {
  8. phaser.arriveAndAwaitAdvance(); // await all creation
  9. task.run();
  10. }
  11. }.start();
  12. }
  13. // allow threads to start and deregister self
  14. phaser.arriveAndDeregister();
  15. }

评论

暂无评论