dk7 and jdk8 of new features

This article is some information I learn about j, are interested in you can browse under the following contents.

Official documents: http: //www.oracle.com/technetwork/java/javase/jdk7-relnotes-418459.html
 
in terms of new features jdk7 mainly to enhance several aspects of the following:
 
1.jdk7 grammatical
 
   represent 1.1 binary variables , supports integer types are represented in binary, begin with 0b.
 
   // all integers int, short, long, byte can be represented by a binary
    //. 8-An 'bit' byte 'value:
    byte aByte = (byte) 0b00100001;
 
    // 16-A' bit 'Short' value:
    Short aShort = ( Short) 0b1010000101000101;
 
    // 32-s Some 'bit' int 'values:
    intanInt1 = 0b10100001010001011010000101000101;
    intanInt2 = 0b101;
    . intanInt3 = 0b101; B // of The CAN BE Upper or Lower Case
 
    // 64-A' bit 'Long' Note value. The "L" suffix:
    Long ALONG = 0b1010000101000101101000010100010110100001010001011010000101000101L;
 

    final int[] phases = { 0b00110001, 0b01100010, 0b11000100, 0b10001001,
    0b00010011, 0b00100110, 0b01001100, 0b10011000 };
 
1.2  Switch语句支持string类型 
 
       public static String getTypeOfDayWithSwitchStatement(String dayOfWeekArg) {
         String typeOfDay;
         switch (dayOfWeekArg) {
             case "Monday":
                 typeOfDay = "Start of work week";
                 break;
             case "Tuesday":
             case "Wednesday":
             case "Thursday":
                 typeOfDay = "Midweek";
                 break;
             case "Friday":
                 typeOfDay = "End of work week";
                 break;
             Case "Saturday":
             Case "the Sunday":
                 typeOfDay = "Weekend";
                 BREAK;
             default:
                 the throw new new an IllegalArgumentException ( "Invalid Day of The Week:" + dayOfWeekArg);
         }
         return typeOfDay;
    } 
 
1.3 the Try-with-Resource statement 
   
  Note: resources to achieve java.lang.AutoCloseable interface can be placed in the try, with the final closure of resources which is similar; they are declared in reverse order to close the resource; try block exceptions thrown obtained by Throwable.getSuppressed 
 
    try (java.util.zip.ZipFile = new new java.util.zip.ZipFile with ZF (zipFileName);
    java.io.BufferedWriter Writer = java.nio.file.Files 
    .newBufferedWriter (outputFilePath, charset)) {
    // the 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 {
    }
 
for 1.5 digital type underlined friendly representation, but to pay attention to some of the standard Underline, refer to the following example
 
    Long the creditCardNumber = 1234_5678_9012_3456L;
    Long socialSecurityNumber = 999_99_9999L;
    a 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; not CAN PUT A decimal underscores Adjacent to Point
    // float pi2 = 3._1415F; // Invalid ; can not 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 = 5_______2;        // 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 
    X9 = 0_52 int; // the OK (Octal literal)
    int = X10 05_2; // the OK (Octal literal)
    // int X11 = 052_; // Invalid; PUT underscores AT CAN Not A Number of The End 
    1.6 generic instance created type inference can be simplified by removing the new generic type rear portion, only <> it.
      // Use the generic prior 
    List = new new strlist the ArrayList (); 
    List <String> = new new strList4 the ArrayList <String> (); 
    List <the Map <String, List <String >>> = new new strList5 the ArrayList <the Map <String, List <>>> String ();
 
      
    // compiler to use angle brackets (<>) concluded that the type of 
    List <String> = new new strList0 the ArrayList <String> (); 
    List <the Map <String, List <String >>> = new new strList1 ArrayList <Map <String, List <  String >>> ();

    List <the Map <String, List <String >>> = new new strList3 the ArrayList <> ();
    List <String> = new new List the ArrayList <> ();
    List.add ( "A");
      // Should Statement of The following Fail the expects the addAll Operating since
      // Collection <String the extends?>
    //list.addAll(new the ArrayList <> ()); 
 
1.7 non-specific transmission parameters in the variable parameters of the method, an improved compilation errors and warnings 
 
Heap pollution means is a variable point another type of variable is not the same. E.g.
 
    List new new L = the ArrayList <Number The> ();
    List <String> LS = L; // an unchecked warning
    l.add (0, new new Integer (42 is)); // Another warning an unchecked
    String ls.get S = (0 ); // a ClassCastException thrown IS
    JDK7:
    public static <T> void AddToList (List <T> listArg, T ...

    listArg.add (X);
    }
    }
    you will get a warning
    warning: [varargs] Possible heap Pollution from the vararg type Parameterized
    To eliminate Warning, there are three ways
    1. Add @SafeVarargs Annotation
    2. add annotation @SuppressWarnings ({ "unchecked "," varargs "})
    3. use the compiler parameters -Xlint: varargs;
 
  1.8 more informative backtracking is above the try and try statement inside the statement while throwing an exception, the exception stack of information
 
    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)? 
    §? Suppress.main AT (Suppress.java:9)  
    § Suppressed:? java.io.IOException 
    §? AT Suppress.close (Suppress.java:24)  
    §? AT Suppress.main (Suppress.java:9) 
      
 
new features 2. NIO2 of
     
    1.java.nio.file and java.nio.file.attribute support package more detailed properties, such as rights, owner 
    2. symbolic and hard links support 
    3. Path access the file system, supports a variety of file operations files 
    4. efficient access metadata information 
    5. recursive search file tree, the file expanded search 
    6. file system modify the notification mechanism 
    7.File operation based API compatibility 
    8. enhanced random access file mapping a region, locl a region, the absolute position read 
    9. AIO Reactor (event-based) and Proactor 
 
  Some examples are listed below:
 
2.1IO monitor file and the IO New system change notification 
 
obtain watchService by FileSystems.getDefault (). newWatchService (), then the path will need to listen to this watchservice registered in the directory, this directory for files to modify, add, delete, etc. can be configured to practice, and then you can automatically monitor in response to the incident.
 
    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;
    }
 
2.2 New the IO and the IO file tree traversal, through inheritance SimpleFileVisitor class implementing event tree traversal operations, then Files.walkFileTree (listDir, opts, Integer.MAX_VALUE, walk ); API to traverse the directory tree
 
    Private void workFilePath () {
    the Path listdir = Paths.get ( "/ tmp"); // the DEFINE Starting File 
    ListTree new new ListTree Walk = ();
    ... Files.walkFileTree (listdir, Walk) ; ...
    // trackers when traversing
    EnumSet the opts = EnumSet.of (FileVisitOption.FOLLOW_LINKS);
    the try {
    Files.walkFileTree (listdir, the opts, Integer.MAX_VALUE, Walk);
    } the catch (IOException E) {
    System.err.println (E);
    }
    class ListTree the extends SimpleFileVisitor <the Path> {// recursive traversal NIO2 file directory interface 
    @Override
    FileVisitResult postVisitDirectory public (the Path the dir, IOException EXC) {
    System.out.println ( "Visited Directory:" + dir.toString ());
    return FileVisitResult.CONTINUE;
    } 
    @Override
    public FileVisitResult visitFileFailed (the Path File, IOException EXC) {
    the System .out.println (EXC);
    return FileVisitResult.CONTINUE;
    }
    }
 
 
2.3 and the AIO asynchronous IO network asynchronous IO file in Java 
 NIO2 achieved, are realized by AsynchronousFileChannel, AsynchronousSocketChanne the like, on synchronous blocking IO, IO nonblocking synchronous, asynchronous blocking and non-blocking asynchronous IO IO in this page below ppt notes have explained, interested insight into the next. Java NIO2 achieved in the operating system asynchronous non-blocking IO.
 
    // use AsynchronousFileChannel.open (path, withOptions (),  
        // taskExecutor)) This API processing of asynchronous file 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 the ByteBuffer Call () throws Exception {  
                            the ByteBuffer Buffer = the ByteBuffer  
                                    .allocateDirect (ThreadLocalRandom.current ()  
                                            .nextInt (100, 200 is));  
                            asynchronousFileChannel.read (Buffer, ThreadLocalRandom  
    ......
 
         
3. the JDBC 4.1
 
. 3.1 may be used try- with-resources automatically shut down Connection, ResultSet, and statement resource objects 
 
3.2 RowSet 1.1:. RowSetFactory introduction of interfaces and RowSetProvider class, you can create a variety of row sets JDBC driver support, rowset actually achieve here is to transfer some operations on the sql statement a method for the operation of, encapsulate some functions.
 
3.3. the ODBC driver deletes the JDBC-in jdk8 
 
    the try (con.createStatement the Statement stmt = ()) { 
     AFactory = RowSetProvider.newFactory the RowSetFactory ();
      the CachedRowSet aFactory.createCachedRowSet CRS = ();
       
     the RowSetFactory RowSetProvider.newFactory RSF = ( "com.sun.rowset.RowSetFactoryImpl", null);
    the WebRowSet rsf.createWebRowSet WRS = ();
    createCachedRowSet 
    createFilteredRowSet 
    createJdbcRowSet 
    createJoinRowSet 
    createWebRowSet 
 
 
4. complicated tools enhanced 
 
4.1.fork-join 
 the greatest enhancement, take advantage of multicore characteristic, splitting large problem into individual sub-problems, a plurality of a plurality of sub-problems can be solved cpu Meanwhile, the final results were combined, inheritance RecursiveTask, compute achieve method, and then call fork computing, and finally join the combined results.
 
    the extends the Fibonacci RecursiveTask class <Integer> {
    Final n-int;
    the Fibonacci (n-int) {
    this.n n-=;
    }
    Private int Compute (int Small) {
    Final int [] Results = {. 1,. 1, 2,. 3,. 5,. 8, 13 is, 21 is, 34 is, 55, 89};
    return Results [Small];
    }
    public Integer Compute () {
    IF (n-<= 10) {
    return Compute (n-);
    }
    the Fibonacci the Fibonacci new new F1 = (n--. 1);
    the Fibonacci the Fibonacci new new F2 = (n-- 2);
    System.out.println ( "for the fork new new Thread" + (n--. 1));
    f1.fork ();
    System.out.println ( "for the fork new new Thread" + (n-- 2));
    f2.fork ();
    return f1.join () + f2.join ();
    }
    } 
 
 4.2.ThreadLocalRandon the random number generator based concurrent ensure thread safety in concurrent random number generated is actually used 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<Runnable> tasks) {
    final Phaser phaser = new Phaser(1); // "1" to register self
    Create and Start Threads //
    for (Final the Runnable Task: Tasks) {
    phaser.register ();
    new new the Thread () {
    public void RUN () {
    phaser.arriveAndAwaitAdvance (); // All the await Creation
    task.run ();
    }
    .start} ();
    }
    // Start the allow Threads and to deregister, or Self
    phaser.arriveAndDeregister ();
    } 
 
5. the Networking enhanced 
 
when new URLClassLoader close methods, resources can be closed in time, a subsequent class file does not cause reloading resources are occupied problem can not be released or
URLClassLoader.newInstance (new URL [] {} ) close ();.
new Sockets direct Protocol
data copying bypass the operating system of the machine from a memory data directly to another via a data network machine memory 
 
6. Multithreaded Custom Class Loaders  
     
    To solve the deadlock could lead to concurrent load class, this is some of the new version of jdk1.6 solved, jdk7 also made some optimization. Interested can carefully from the official documentation for further details
 
before JDK7:
   
    Class Hierarchy:            
      class A the extends B
      class C the extends D
    ClassLoader Delegation Hierarchy:
    Custom the Classloader CL1:
      Directly loads class A 
      Delegates to Custom ClassLoader CL2 for class B
    Custom the Classloader CL2:
      Directly loads class C
      Delegates to class D Custom ClassLoader CLl for
    the Thread. 1:
      the Use Load CLl to class A (Locks CLl)
        the defineClass A Triggers
          the loadClass B (Lock CL2 is the try to)
    the Thread 2:
      the Use CL2 is to class C Load (CL2 is Locks)
        the defineClass C Triggers
          the loadClass D (the try to Lock CLl)
    Synchronization in The ClassLoader class WA 
 
JDK7
 
    the Thread. 1:
      the Use CLl to Load class A (Locks CLl + A)
        the defineClass A Triggers
          the loadClass B (Locks CL2 is + B)
    the Thread 2:
      the Use CL2 is to class C Load (CL2 is Locks + C)
        the defineClass C Triggers
          the loadClass D (D + CLl Locks) 
 
 
7. The enhanced Security 
 
    7.1 providing several-based algorithms the ECC (the ECDSA / the ECDH) Elliptic the Curve Cryptography (the ECC)
    7.2. disabled CertPath Algorithm disabling
    7.3. JSSE (SSL / TLS) Some enhancement 
 
8. Internationalization adds support for reinforcing and increasing the number of encoded encoding settings of some other aspects of the display
     
    1. New Scripts and Characters from Unicode 6.0.0
    2. Extensible Support for ISO 4217 Currency Codes
    Currency类添加:      
           getAvailableCurrencies 
           getNumericCode 
           getDisplayName 
           getDisplayName(Locale)
    3. Category Locale Support
     getDefault(Locale.Category)FORMAT  DISPLAY 
    4. Locale Class Supports BCP47 and UTR35
           UNICODE_LOCALE_EXTENSION
           PRIVATE_USE_EXTENSION
           Locale.Builder 
           getExtensionKeys()
           getExtension(char)
           getUnicodeLocaleType(String
            ……
    5. New NumericShaper Methods
    NumericShaper.Range 
    getShaper (NumericShaper.Range) 
    getContextualShaper (the Set <NumericShaper.Range>) ...... 
 
 
some of the features 9.jvm aspects enhancements, here are some characteristics already present in jdk6 in here to do some optimization and enhancements.
 
1.Jvm support non java language instruction invokedynamic 
 
2. Garbage-First Collector for the server side, the large memory multiprocessor, a plurality of the heap into equal size areas, mark detecting viable target phase for each region, compress stage do first smallest surviving objects recovered, this will free up a lot of free area, so concurrent recovery of other regions will be able to reduce stopping time and increase throughput. 
 
3. HotSpot performance enhancement 
    Tiered Compilation -XX: + UseTieredCompilation multilayer compiled code directly to native code compilation process frequently called, improve the efficiency
   Compressed Oops object pointer compression, to reduce the space used
  Zero-Based Compressed Ordinary Object Pointers ( oops) further optimization of zero-base object pointer compression, further compression space
 
4. escape analysis escape analysis, only for some variables used in a method, assignment can be directly on the stack, release the memory automatically executing the method, instead of the object referenced by the stack reference objects in the heap, then the target for recovery may not be so in a timely manner.
 
5. NUMA Collector Enhancements  
 
NUMA (Non Uniform Memory Access), NUMA computer system in a variety have been realized, in short, is to access the memory segment, similar to the RAID disk, the Oracle cluster 
 
10. The the Java 2D Enhancements
 
    1. the XRender Rendering the Pipeline -Dsun.java2d.xrender = True -Based
    2. Support for OpenType / Fonts the GraphicsEnvironment.getAvailableFontFamilyNames the CFF 
    3. Support for the TextLayout Tibetan Script
    4. Support for the Linux Fonts
 
11. The Enhancements the Swing
 
    1. JLayer 
    2. the Nimbus Look & Feel
    . 3 . Heavyweight and Lightweight Components
    4. Translucent and Shaped Windows
    5. Hue-Saturation-Luminance (HSL) Color Selection in a JColorChooser Class
 
 
 
12. Jdk8 the lambda expression is the biggest new features, but in many dynamic languages have native support.
 
The original write:
 
    btn.setOnAction(new EventHandler<ActionEvent>() { 
        @Override
        public void handle(ActionEvent event) { 
            System.out.println("Hello World!"); 
        } 
    }); 
        
jdk8直接可以这么写:
 
    btn.setOnAction( 
        event -> System.out.println("Hello World!") 
    );   
        
更多示例:
    
    public class Utils { 
        public static int compareByLength(String in, String out){ 
            return in.length() - out.length(); 
        } 
    } 
 
    public class MyClass { 
        public void doSomething() { 
            String[] args = new String[] {"microsoft","apple","linux","oracle"} 
            Arrays.sort (args, Utils :: compareByLength); 
        }  
    }  
 
Some other features 13.jdk8, of course, there are many enhancements jdk8, we can refer to http://openjdk.java.net/projects/jdk8/
 
with Metaspace Instead of PermGen 
dynamic expansion, the maximum value may be provided, to limit the size of the local memory 
Parallel array sorting # parallelSort new APIArrays.
 
    new the API a Date & Time
    Clock Clock Clock.systemUTC = (); // return your the Current System Time Clock based oN and UTC to the SET.
 
    Clock Clock = Clock.systemDefaultZone (); // return based ON System Clock Time Zone 
 
    Long Time = clock.millis (); // Time in milliseconds from January 1st, 1970

Guess you like

Origin www.cnblogs.com/isme-zjh/p/11442977.html