New features of Jdk7

Source: Internet
Author: User

Tags:

There are several enhancements to the new features of JDK7: The representation of the 1.1 binary variables in the 1.JDK7 syntax, which supports the binary representation of the integer type and begins with 0b. All integer int, short,long,byte can be expressed in binary notation//an 8-bit ' byte ' value:byte abyte = (byte) 0b00100001;//A 16-bit ' short ' Value:sho RT 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;// binary in arrays, etc. final int[] phases = {0b00110001, 0b01100010, 0b11000100, 0b10001001,0b00010011, 0b00100110, 0b01001100, 0b100 11000};1.2 switch statement supports string type public static string Gettypeofdaywithswitchstatement (String dayofweekarg) {String type Ofday; Switch (dayofweekarg) {case ' Monday ': typeofday = ' Start of work week '; break, Case ' Tuesday ': Case ' Wednesday ': Case ' Th Ursday ": Typeofday =" midweek "; Break Case "Friday": Typeofday = "End of work Week"; Break Case "Saturday": Case "SuNday ": Typeofday =" Weekend "; Break Default:throw new IllegalArgumentException ("Invalid Day of the week:" + Dayofweekarg);} return typeofday;} 1.3 Try-with-resource Statement Note: Resources that implement java.lang.AutoCloseable interfaces can be placed in a Try, similar to closed resources in final, and closed in reverse order of declarations; The exception thrown by the try block gets the try by throwable.getsuppressed (java.util.zip.ZipFile ZF = new Java.util.zip.ZipFile (zipfilename); Java.io.BufferedWriter writer = java.nio.file.Files. Newbufferedwriter (Outputfilepath, CharSet)) {//Enumerate each Entryfor (java.util.Enumeration entries = Zf.entries (); entries.hasmoreelements ();) {//Get the entry name and write it to the output filestring NewLine = System.getproperty ("Line.separator"); String Zipentryname = ((java.util.zip.ZipEntry) entries.nextelement ()). GetName () + Newline;writer.write (zipentryname , 0, Zipentryname.length ());}} 1.4 Catch Multiple Exception Description: The catch exception type is final, the build bytecode is smaller than multiple catch, rethrow when you leave the exception type public static void Main (string[] args) throws Exce ption {try {testthrows ();} catch (IOException | SQLException ex) {THRow ex;}} public static void Testthrows () throws IOException, SQLException {The underscore for the}1.5 number type represents a more friendly representation, but pay attention to some of the criteria added by the underscore, You can refer to the following example 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;lon G 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;              A identifier, not a numeric literalint x2 = 5_2;              OK (decimal literal)//int x3 = 52_; Invalid;        Cannot put underscores at the end of a literalint 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 numberint 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 the creation of a generic instance can be simplified by type inference to simplify the generic type that can be removed from the next new section, using only <>. Use generic before List strlist = new ArrayList (); list<string> strList4 = new arraylist<string> (); list<map<string, list<string>>> strList5 = new arraylist<map<string, list<string>> > (); The compiler uses angle brackets (<>) to infer the type list<string> strList0 = new arraylist<string> (); list<map<string, list<string>>> strList1 = new arraylist<map<string, list<string>> > (); list<string> strList2 = new arraylist&Lt;> (); 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<> ()); 1.7 Passing non-materialized parameters in a Variadic method, improving compilation warnings and errors Heap pollution refers to a variable that is pointed to another variable that is not of the same type. For example, list L = new arraylist<number> ();       list<string> ls = l; Unchecked Warningl.add (0, New Integer (42));      Another unchecked warningstring s = ls.get (0); ClassCastException is thrownjdk7:public static <T> void Addtolist (list<t> listarg, t ... elements) {for (t x:elements) {listarg.add (x);}} You'll get a warningwarning: [varargs] Possible heap pollution from parameterized vararg type to eliminate the warning, there are three ways to do 1. Plus annotation @  Safevarargs 2. Add annotation @SuppressWarnings ({"Unchecked", "VarArgs"}) 3. Use compiler parameters –xlint:varargs;      1.8 Information Richer backtracking is the information java.io.ioexception§ of the exception stack when the try statement in the above try and the inside statement throw an exception at the same time? 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.  Some of the new features of NIO2 1.java.nio.file and Java.nio.file.attribute packages support more detailed properties, such as permissions, owner 2. Symbolic and hard links support 3. Path accesses file system, files supports various file operations 4. Efficient access to metadata information 5. Recursively find file tree, file extension Search 6. File system modification notification mechanism 7.File class action API compatible 8. File random access enhanced mapping a region, Locl a region, absolute position read 9. AIO Reactor (Event-based) and proactor below are some examples: 2.1IO and New IO Listener file system change notification via Filesystems.getdefault (). Newwatchservice () Get Watchservice, and then register the path directory that needs to listen to this watchservice, for this directory of file modifications, additions, deletions and other practices can be configured, and then automatically listen to the response of the event. 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<?> Eve Nt:key.pollEvents ()) {Watchevent.kind Kind = Event.kind (); if (Kind = = OVERFLOW) {//event may lost or discardedcontinue;} 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 io and New io traverse the file tree by inheriting the Simplefilevisitor class, implementing an event traversal of the directory tree, and then through Files.walkfiletree (Listdir, opts, Integer.max_value, walk); This API to traverse the directory tree private void Workfilepath () {Path Listdir = Paths.get ("/tmp");//define the starting file Listtree walk = new Listtree (); .... Files.walkfiletree (Listdir, walk);//The trace link Enumset opts = enumset.of (filevisitoption.follow_links) during traversal; try { Files.walkfiletree (Listdir, opts, Integer.max_value, walk);} catch (IOException e) {System.err.println (e);} Class Listtree extends Simplefilevisitor<path> {//NIO2 recursively traverse the directory interface of the file @OverridepubliC Filevisitresult postvisitdirectory (Path dir, IOException exc) {System.out.println ("visited directory:" + dir.tostring ()); return filevisitresult.continue;} @Overridepublic filevisitresult visitfilefailed (Path file, IOException exc) {System.out.println (exc); return Filevisitresult.continue;}} 2.3 Aio Asynchronous IO files and network asynchronous IO are implemented in Java NIO2, and are implemented with Asynchronousfilechannel,asynchronoussocketchanne, for synchronous blocking IO, synchronous non-blocking IO, Asynchronous blocking IO and asynchronous non-blocking IO on this page of PPT are described below, and interested can be learned in depth. Asynchronous non-blocking IO of the operating system is implemented in Java NIO2. Using Asynchronousfilechannel.open (Path, withoptions (),///Taskexecutor) This API handles 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 <; i++) {callable<bytebuffer> worker = new callable<bytebuffer> () {@Over Ride public Bytebuffer Call () throws Exception {Bytebuffer buffer = Bytebuffer. Allocatedirect (Threadlocalrandom.curre  NT (). Nextint (100, 200)); Asynchronousfilechannel.read (buffer, threadlocalrandom ... 3. JDBC 4.13.1. You can use Try-with-resources to automatically turn off connection, ResultSet, and statement resource Object 3.2. RowSet 1.1: Introducing the Rowsetfactory interface and Rowsetprovider class, you can create various row sets supported by the JDBC driver, where the RowSet implementation is actually the operation of converting some operations on the SQL statement to the method, Encapsulates a number of features. 3.3. Jdbc-odbc driver removes try (Statement stmt = Con.createstatement ()) in Jdk8 {rowsetfactory afactory = Rowsetprovider.newfacto  Ry ();   CachedRowSet CRS = Afactory.createcachedrowset (); Rowsetfactory RSF = rowsetprovider.newfactory ("Com.sun.rowset.RowSetFactoryImpl", null); Webrowset WRs = Rsf.createwebrowset (); Createcachedrowset createfilteredrowset Createjdbcrowset CreateJoinRowSet Createwebrowset 4. Concurrency tool enhances 4.1.fork-join maximum, maximizes multi-core features, decomposes large issues into sub-problems, and multiple CPUs can solve multiple sub-problems at the same time, finally merges the result, inherits the Recursivetask, implements the compute method, then calls the fork computation, and finally merges the result with the join. 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,,,, and};return];} Public Integer Compute () {if (n <=) {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 concurrent random number generation class, to ensure that the concurrent random number generation of thread safety, is actually using threadlocal final int MAX = 100000; Threadlocalrandom threadlocalrandom = Threadlocalrandom.current (); Long start = System.nanotime (); for (int i = 0; i < MA X 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 similar to Cyclebarrier and Countdownlatch, but can dynamically add resources to reduce resource void runtasks (list<runnable> tasks) {Final Phaser Phaser = new Phaser (1); "1" To register self//Create and start threadsfor (final Runnable task:tasks) {phaser.register (); new Thread () {Publi c void Run () {phaser.arriveandawaitadvance ();//await All creationtask.run ();}}. Start ();} Allow threads to start and deregister selfphaser.arriveandderegister ();} 5. Networking enhanced the new URLClassLoader Close method, you can close the resource in a timely manner, subsequent reloading of the class file will not cause the resource to be occupied or to release the problem Urlclassloader.newinstance (new url[]{}). Close (); New sockets direct protocol bypasses the operating system's data copy, transferring data from one machine's memory data directly to the memory of another machine 6. Multithreaded Custom class loaders solve the deadlock problem that can result from loading class, this is jdk1.6 some new version is solved, JDK7 also did some optimizations. Interested can carefully learn more about JDK7 before the Official document: Class Hierarchy:class A extends B class C extends Dclassloader delegation Hierarchy : Custom Classloader cl1:directly loads class A delegates to Custom Classloader CL2 for Class Bcustom Classloader cl2:directly loads class C delegates to custom Classloader CL1 for class Dthread 1:use CL1  To load Class A (locks CL1) defineclass a triggers loadclass B (try-to-lock CL2) Thread 2:use CL2 to load class C (locks CL2) DefineClass c triggers loadclass D (try to lock CL1) synchronization in the ClassLoader class WA Jdk7thread 1:use C  L1 to load class A (locks cl1+a) defineclass A triggers loadclass B (locks cl2+b) Thread 2:use CL2 to load class C (locks CL2+C) defineclass C triggers loadclass D (locks cl1+d) 7. Security Enhancements 7.1. Provides several ecc-based algorithms (ECDSA/ECDH) Elliptic Curve Cryptography (ECC) 7.2. Disable Certpath algorithm Disablin Some enhancements to g7.3. JSSE (SSL/TLS) 8. Internationalization enhancements have added support for some encodings and added some coding settings for display aspects such as 1. New Scripts and characters from Unicode 6.0.02. Extensible support for ISO 4217 Currency codescurrency class add: Getavailablecurrencies getnumericcode Getdisplayn Ame 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 Getextensionk Eys () getextension (char) getunicodelocaletype (String ...). 5. New numericshaper methodsnumericshaper.range getshaper (numericshaper.range) getcontextualshaper (Set< numericshaper.range>) ... Some features of the 9.JVM are enhanced, some of which are already present in jdk6, and some optimizations and enhancements are made here. 1.JVM supports non-Java language invokedynamic instruction 2. Garbage-first Collector is suitable for server side, large memory under multiprocessor, divide the heap into multiple areas of equal size, mark phase detects the surviving objects in each region, and the compress phase will recover the smallest surviving objects first, which frees up many free areas , which can reduce the stop time and increase throughput by concurrently reclaiming other regions. 3. Hotspot performance Enhancement tiered compilation-xx:+usetieredcompilation multi-layer compilation, for frequently called code will directly compile the local code, improve efficiency compressed Oops compression object pointer, minus Less space using zero-based compressed ordinary object pointers (oops) further optimizes the zero-base compression object pointer, further compressing space 4. Escape Analysis Escape Analytics, for just a few variables used in a method, you can directly assign the object to the stack, the method executes the automatic free memory, instead of referencing the object in the heap through the object reference of the stack, the collection of objects may not be so timely. 5. Numa Collector Enhancements Numa (Non Uniform Memory Access), NUMA is implemented in a variety of computer systems, in short, segmented memory access, similar to hard disk raid, Cluster 10 in Oracle. Java 2D EnHancements1. Xrender-based Rendering pipeline-dsun.java2d.xrender=true2. Support for OPENTYPE/CFF Fonts Graphicsenvironment.getavailablefontfamilynames 3. TextLayout support for Tibetan Script4. Support for Linux FONTS11. Swing enhancements1.jlayer 2.Nimbus Look & Feel3.heavyweight and lightweight components4.shaped and translucent Windo Ws5. Hue-saturation-luminance (HSL) Color Selection in JColorChooser Class12. The Jdk8 lambda expression is the most new feature, but is natively supported in many dynamic languages. Originally written: Btn.setonaction (new eventhandler<actionevent> () {@Override public void handle (ActionEvent event) { System.out.println ("Hello world!");        } });      Jdk8 directly can write this: Btn.setonaction (event, System.out.println ("Hello world!")); More examples: public class Utils {public static int comparebylength (string of, 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); }  }  13.jdk8 Some other features, of course, JDK8 enhancements There are many, we can refer to http://openjdk.java.net/projects/jdk8/with metaspace instead of PermGen dynamic expansion, you can set the maximum value, Size limited to local memory Parallel array sorting new apiarrays#parallelsort.new Date & time Apiclock Clock = CLOCK.SYSTEMUTC (); Return the current time based on your system clock and set to UTC. Clock Clock = Clock.systemdefaultzone (); Return time based on system clock zone long time = Clock.millis ();  Time in milliseconds from January 1st, 1970

New features of Jdk7

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

Tags Index: