JDK Frame--java.util Wrapper tool Library

Source: Internet
Author: User
Tags iterable concurrentmodificationexception


Inscription


Jdk,java Development Kit.

First, we have to realize that, JDK but, but set Java to only the base Class library. It was developed by sun through the base class library, which is unique. The JDK writes a summary of the class library. They all need to be compiled into bytecode in terms of technical content or at one level. Performed in the JRE. The result of the JDK compilation is the Rt.jar under Jre/lib. We learned to use it to deepen our understanding of Java and to improve our Java coding level.

All articles in this series are based on the JDK version number 1.7.16.

Source code: https://jdk7.java.net/source.html


The content of this section


In this section. A brief analysis of the tool class Library included in the Java.util package. It is mainly a collection of related class libraries, followed by regular, compressed decompression, concurrency, date and time, and other tool classes.

This article is a brief description of the Java.util package. The content will be supplemented gradually in the future. This article is equivalent to a placeholder, the so-called first skeleton, talent gradually plump


Collection Class


Basic situation


The main interfaces and their inheritance relationships are as follows:

SortedSet---Collection---iterable

List--Collection--iterable

SortedMap-Map

Frequently use classes and their inheritance relationships such as the following:

Hashset/linkedhashset---Set

TreeSet--SortedSet and Set

Arraylist/linkedlist-List

HashMap-Map

TreeMap--SortedMap-Map


Unified appellation: Collection Branch, we call it "aggregation". Map Branch, which we call "mapping".

Collection inherits from Iterable, so the classes below can be iterator with an iterator and can be used for access in the form of a for (E e:es); Map can use an object that implements its internal interface entry as an element.

Hashtable and HashMap, they all implement the map interface, Hashtable inherit from the ancient abstract class dictionary. is thread-safe; HashMap inherits from the newer abstract class Abstractmap, not thread-safe.

HashMap the key and value that agree to null. The Hashtable does not agree with the null key and value, which is due to:

Hashtable has a method contains method (inferring whether there is a value), assuming consent. Either key or value NULL will return NULL, which is easy to misunderstand. So Hashtable is forced to restrict, for null keys and values. Direct throw nullpointerexception;

HashMap There is no contains method. Each is ContainsKey () and Containsvalues ().

In addition JDK5 started, for the thread-safe map, there is a concurrenthashmap, efficient, in fact, thread-safe process, no use of synchronized. is a segmented structure, and thread safety is achieved by using a non-locking algorithm such as CAs.


Hash


The object class has two methods to determine the identity of the objects: Equals () and hashcode ().

Generally speaking. Suppose you ignore one of these, you must ignore both at the same time, because there is a vital relationship between the two that must be maintained.

The special case is based on the Equals () method, assuming that two objects are equal. They must have the same hashcode () value, which is required in the object source code. Although this is usually not true.

Http://blog.sina.com.cn/s/blog_5dc351100101l57b.html

http://fhuan123.iteye.com/blog/1452275

About HashMap source code analysis, can participate in: http://github.thinkingbar.com/hashmap-analysis/

Linkedhashmap, rewrite the HashMap iterator, AddEntry, entry, and several other methods and classes, with a doubly linked list to store the order of the elements added. This can be sorted according to the order of the interview, the recently visited element (Get/put), will be placed at the end of the list, which is the LRU algorithm (Least recenty used). Least recently used algorithms.


ArrayList and LinkedList


About ArrayList and Linkedlist,arraylist are array-based, in such a way that the object is placed in a continuous position, read fast, but the capacity is insufficient when the array expansion, performance reduction, insertion and deletion is also slow; LinkedList is based on a linked list, Insertions and deletions are quick, but looking for trouble cannot be looked up according to the index. So. For the construction of a queue is ArrayList or LinkedList, is based on performance and convenience to consider, for example LinkedList has Removelast (), ArrayList can only remove (index), Use LinkedList to construct a queue code demo sample such as the following:

Class Queue {private linkedlist<string> llt;public queue () {llt = new linkedlist<string> ();} public void Add (String s) {llt.add (s);} Public String get () {return llt.removelast ();//Queue//return Llt.removefirst ();//Stack}public boolean isNull () {return Llt.isempty ();}}


Concurrentmodificationexception


import Java.util.*;import java.util.map.entry;class test{public static void Main (string[] args) throws Exception {hashmap< string,integer> mtemp = new hashmap<string,integer> () mtemp.put ("Test1", 1); Iterator<entry<string, integer>> iTemp = Mtemp.entryset (). iterator ();//The following line of code will cause java.util.concurrentmodificationexception,// After the iterator is created on the aggregation. When traversing or altering the operation. Suppose you encounter a situation where the desired change counter is not the same as the actual change counter (modcount! = Expectedmodcount)//will report this exception, optimistic locking thought//mtemp.put ("Test2", 2); while ( Itemp.hasnext ()) {System.out.println (Itemp.next (). GetKey ());} For loops, the notation is simpler, and after compilation, it is converted to an iterator for (entry<string,integer> E:mtemp.entryset ()) {System.out.println (E.getkey ( ));} Arraylist<string> al = new arraylist<string> (); Al.add ("test"); for (string s:al) {Integer i = Integer.reverse (New Java.util.Random () Nextint ()); Al.add (i.ToString ());//This line of code will also be reported concurrentmodificationexception}}} 

In this case, you can use the relevant classes in the Java.util.concurrent package, such as copyonwritearraylist, not to report this exception. Because the Copyonwritearraylist class is the biggest feature. In the case of the actual change operation (Add/remove, etc.) will create a new data and changes. After the change is complete, point the original reference to the new array.

Thus, the change process does not change the original array, there is no concurrentmodificationexception error.

We are able to participate in the source code of Copyonwritearraylist:

    /**     * Appends the specified element to the end of this list.     *     * @param e element to is appended to the list     * @return <tt>true</tt> (as specified by {@link Colle Ction#add})     *    /public boolean add (E e) {        final reentrantlock lock = This.lock;        Lock.lock ();        try {            object[] elements = GetArray ();            int len = elements.length;            object[] newelements = arrays.copyof (elements, Len + 1);            Newelements[len] = e;            SetArray (newelements);            return true;        } finally {            lock.unlock ();        }    }

Concurrentmodificationexception. Indicates: What I am reading is changed, do you need to traverse again? Or do any other processing? This is the meaning of the fast-fail (high-speed failure mechanism).

Although this is only within a thread, not multithreaded, we can also understand the same fast-fail:

Fail-fast is a detailed application of the concurrency optimistic (optimistic) strategy. It agrees that the thread is free to compete, but if you can handle it in the event of a conflict, you can infer what the problem is and give a solution;

The pessimistic (pessimistic) strategy is just the opposite. It is always pre-set enough limits, usually by the use of locks (lock), to ensure that the process of error-free procedures, pay the price of other threads waiting for the cost.


The main purpose of the high-speed failure mechanism is to enable the thread that iterator iterates through the array to discover other threads ' changes to the map (such as put, remove, clear, etc.) in time. therefore Fast-fail is not guaranteed to be a multi-threaded concurrency error in all cases, only to protect Iterator.next () and write concurrency during iterator traversal.


TreeSet and Collections.sort


TreeSet is based on the TREEMAP implementation. The underlying data structure is the "red-black Tree". Data is added in a sequential order, and access and lookup performance is not as good as hashset. Collections.sort is a sort of stable sort by first converting list to array, then using "merge sort" algorithm to order, and merging sort.

Articles about TreeMap:

http://zh.wikipedia.org/wiki/%E7%BA%A2%E9%BB%91%E6%A0%91

Http://www.cnblogs.com/fornever/archive/2011/12/02/2270692.html

http://shmilyaw-hotmail-com.iteye.com/blog/1836431

Http://www.ibm.com/developerworks/cn/java/j-lo-tree/index.html

http://blog.csdn.net/chenhuajie123/article/details/11951777

The performance of the two sorting algorithms is more like the following (24 cores, 64G memory, RHEL6.2):

The number of sorted elements in the case where the data is already in the basic order. Within a segment (approximately 20,000-200,000). TreeSet is more efficient; the other number is collections.sort more efficient;

In the case of data randomness, the number of ordered elements is within 10,000. There is little difference. Collections.sort performance is slightly higher. Beyond 10,000, within 800,000. TreeSet performance is significantly higher than collections.sort. 800,000 away. Collection.sort higher performance. Java.util.concurrent.ConcurrentSkipListSet, which is based on a "skip table" Thread-safe sortable class, has a performance higher than collection.sort within 300,000. 300,000 away. Performance below Collection.sort,concurrentskiplistset is always less than treeset.

The advantage of having a balanced tree-like index concurrentskiplistset is that it behaves very well in a concurrent environment.

It can be imagined that before the data structures such as skiplist are not known. If you want to construct a sort-based index structure in a concurrent environment, then the red-black tree is a better choice, but its balancing operation requires locking the entire tree structure, so performance and scalability in the concurrency environment is not good.

The Code demo sample is as follows:

Import Java.util.treeset;import java.util.arraylist;import java.util.comparator;import java.util.Collections;        Import java.util.arrays;import java.util.listiterator;import java.util.random;import java.util.Iterator;class Test {                public static void Main (string[] args) {final int LEN = 300000;                final int SEED = 100000;                Random r = new Random ();                System.out.println ("---------------------------");                Long B = System.currenttimemillis (); treeset<temp> ts = new treeset<temp> (new comparator<temp> () {public int compare (T                EMP t1,temp T2) {return t1.id-t2.id;}                });                for (int i=0;i<len;i++) {Ts.add (New Temp (R.nextint (SEED)));                } System.out.println (System.currenttimemillis ()-B);                Arraylist<temp> atemp = new arraylist<temp> (); Iterator<temp>it = Ts.iterator ();                while (It.hasnext ()) {Atemp.add (It.next ());                } System.out.println (System.currenttimemillis ()-B);                System.out.println ("---------------------------");                b = System.currenttimemillis ();                Arraylist<temp> al = new Arraylist<temp> ();                for (int i=0;i<len;i++) {Al.add (New Temp (R.nextint (SEED))); }//split to the real excution unit/* Collections.sort (al,new comparator<                Temp> () {public int compare (Temp t1,temp T2) {return t1.id-t2.id;}                }); */temp[] A = new temp[al.size ()];                Al.toarray (a);                System.out.println (System.currenttimemillis ()-B); Arrays.sort (a,new comparator<temp> () {public int compare (Temp t1,temp T2) {return t1.id-T2.id;}                });                System.out.println (System.currenttimemillis ()-B);                Listiterator<temp> li = Al.listiterator ();                        for (int i=0;i<a.length;i++) {li.next ();                Li.set (A[i]);        } System.out.println (System.currenttimemillis ()-B);        }}class Temp {public temp (int id) {this.id = ID;} public int id;}

One error authentication:

An error has been verified. Found using TreeSet sorting on an object, and using the same data entry<string,double> to sort the comparison, the performance is very poor. Start thinking that the JDK has been optimized for entry. Static/final or something. Later, the object is also changed to final, the elements are also changed to final. Found performance is still very poor. I can't explain it, I can't understand it.

Later, it was discovered that two pieces of code were inconsistent, and that the code that was sorted with entry had bugs, resulting in very little data being sorted. So it looks good performance ....

So. An unwarranted assumption is not a good idea, based on a deep understanding of the JDK.


Another sort of idea


For example, the top 20 is not necessarily all sorted, can only take the first 20, verified. Small data volumes, performance is also very high, big data is not verified. The code is roughly such as the following:

int n = 0;double Minscore = smallest integral in 100;//top20 String Minkey = "";//Minimum value of keymap<string,double> skutop = new HASHMAP&L T String,double> (); set<string> styles = new hashset<string> ();//filter the same for (String Sku:tempSkuViewSkus.get (Goodsuser.getkey ()) {Boolean filter = False;filter = Filtersamestyle (sku,styles); if filter continue;//is unsuccessful, direct continueset<string > userset = goodsuserview.get (SKU); if (Userset = = NULL | | userset.size () = = 0) continue;//This step, the calculation of integrals, Is the most time-consuming operation (performance bottleneck) Double score = Mathtools.getjaccardsimilar (Goodsuser.getvalue (), userset);//First 20 Direct Access Mapif (n++ < Constmongo.maxrecomnum) {Skutop.put (SKU, SCORE), if (Score < Minscore) {Minscore = Score;minkey = SKU;} Continue;} If (score <= minscore) continue;//replaces the minimum value skutop.remove (Minkey); Skutop.put (SKU, score); Minscore = Score;minkey = SKU; For (entry<string,double> E:skutop.entryset ()) {if (E.getvalue () < Minscore) {Minscore = E.getvalue (); MinKey = E . GetKey ();}}}


The regular form of the expression


Import Java.util.regex.matcher;import Java.util.regex.pattern;public class Hello {public static void main (string[] args {Pattern pattern = pattern.compile ("normal form");//pattern pattern = Pattern.compile ("Hello, Regular Table \\s[\\s]+"); Matcher Matcher = Pattern.matcher ("Regular table" Hello, "normal table");//Replace the first regular data System.out.println (Matcher.replacefirst ( "Java"));}}


Regular expressions are supported in the common development language, but they are different in terms of regular support.

JS Regular: http://msdn.microsoft.com/zh-cn/library/ae5bf541 (vs.80). aspx

Python Regular: http://www.cnblogs.com/huxi/archive/2010/07/04/1771073.html

Java Regular:

Http://www.blogjava.net/xzclog/archive/2006/09/19/70603.html

Http://www.cnblogs.com/android-html5/archive/2012/06/02/2533924.html

Concurrency related classes


For example, the following sections have a simple use demo: http://blog.csdn.net/puma_dong/article/details/37597261#t5


Compression Decompression Class


For example, the following sections have a simple use demo: http://blog.csdn.net/puma_dong/article/details/23018555#t20


Other tools


Timer, date, time, currency

JDK Frame--java.util Wrapper tool Library

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.