前言
以前学习的过程当中,天天都是老师说这个是JDK7之后可使用,那个是JDK8之后可使用,天天都记的很混乱,今天专门忙里偷闲,归拢整理下JDK7的新特性,对于JDK的新特性,后期会进行整理更新,但愿能够帮助到有须要的朋友。java
一,语法上
String s = "test"; switch (s) { case "test" : System.out.println("test"); case "test1" : System.out.println("test1"); break ; default : System.out.println("break"); break ; }
// 全部整数 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 };
注意:实现java.lang.AutoCloseable接口的资源均可以放到try中,跟final里面的关闭资源相似; 按照声明逆序关闭资源 ;Try块抛出的异常经过Throwable.getSuppressed获取sql
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()); } } }
public static void main(String[] args) throws Exception { try { testthrows(); } catch (IOException | SQLException ex) { throw ex; } } public static void testthrows() throws IOException, SQLException {}
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
//使用泛型前 List strList = new ArrayList(); List<String> strList4 = new ArrayList<String>(); List<Map<String, List<String>>> strList5 = new ArrayList<Map<String, List<String>>>(); //编译器使用尖括号 (<>) 推断类型 List<String> strList0 = new ArrayList<String>(); List<Map<String, List<String>>> strList1 = new ArrayList<Map<String, List<String>>>(); List<String> strList2 = new ArrayList<>(); List<Map<String, List<String>>> strList3 = new ArrayList<>(); List<String> list = new ArrayList<>(); list.add("A"); // The following statement should fail since addAll expects // Collection<? extends String> //list.addAll(new ArrayList<>());
Heap pollution 指一个变量被指向另一个不是相同类型的变量。例如数组
List l = new ArrayList<Number>(); List<String> ls = l; // unchecked warning l.add(0, new Integer(42)); // another unchecked warning String s = ls.get(0); // ClassCastException is thrown Jdk7: public static <T> void addToList (List<T> 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;
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)
2、NIO2的一些新特性
经过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<Path> e = (WatchEvent<Path>) event; Path fileName = e.context(); System.out.printf("Event %s has happened,which fileName is %s%n",kind.name(), fileName); } if (!key.reset()) { break; }
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<Path> {// 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; } }
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<Future<ByteBuffer>> 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<ByteBuffer> worker = new Callable<ByteBuffer>(){ @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、并发工具加强
最大的加强,充分利用多核特性,将大问题分解成各个子问题,由多个cpu能够同时解决多个子问题,最后合并结果,继承RecursiveTask,实现compute方法,而后调用fork计算,最后用join合并结果。app
class Fibonacci extends RecursiveTask<Integer> { 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(); } }
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);
void runTasks(List<Runnable> 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(); }
结尾
因为我的能力问题,还有不少须要改进的地方,若有错误,烦请各位大佬私信或留言进行批评指正,在下定当及时更正!dom