Java Collections Tool class method usage and source analysis (i) __java

Source: Internet
Author: User
Tags mutex throw exception

Concept distinction: java.util.Collection and java.util.Collections differences:

1, Java.util.Collection is a collection interface (a top-level interface of the collection Class). It provides a common interface method for basic operations on a collection object. The collection interface has many specific implementations in the Java class Library. The significance of the collection interface is to provide a maximum unified operation for a variety of specific sets, and its direct inheritance interface has a list and set.

2, Java.util.Collections is a packing class (tool class/help Class). It contains a variety of static polymorphic methods about set operations. This class cannot be instantiated, like a tool class, which serves the Java collection framework by sorting, searching, and line Cheng of elements in a collection.


Since collections is a service to the collection framework, then we try to learn to use:

Method 1:

Java.util.Collections.unmodifiableCollection (collection<? extends Double>): Returns the unmodified view of the specified Collection.

Package com.daxin.collections;

Import java.util.ArrayList;
Import java.util.Collection;
Import java.util.Collections;

public class Main1 {public

	static void Main (string[] args) {

		collection<double> list = new Arraylist<dou Ble> ();

		Double array[] = {m, 102, 78,23};
		
		System.out.println ("List.hashcode () 1" +list.hashcode ());

		for (int i = 0; i < Array.Length i++) {
			list.add (array[i]);

		System.out.println ("List.hashcode () 2" +list.hashcode ());
		
		Returns that the view cannot be modified
		collection<double> unmodifiablecollection = collections.unmodifiablecollection (list);

		Unmodifiablecollection.add (1.2);//Throw exception for

		(Double d:unmodifiablecollection) {
			System.out.println (d);
		}
	}
}

An exception is thrown when we call Unmodifiablecollection.add (1.2) on the returned unmodified view:

Exception in thread ' main ' java.lang.UnsupportedOperationException at
	java.util.collections$ Unmodifiablecollection.add (collections.java:1075) at
	Com.daxin.collections.Main1.main (main1.java:24)

How is it that the implementation cannot be modified? Answer: Use the agent mode, the specific process to see the source code as follows:

The non modifiable view type returned is: Java.util.collections.unmodifiablecollection<e>, is a static inner class of collections, And the Unmodifiablecollection method is implemented as follows:

    public static <T> collection<t> unmodifiablecollection (collection<. extends t> c) {return
        new Unmodifiablecollection<> (c);
    }

Where C is a member of the Unmodifiablecollection class:

 	Final collection<? Extends e> C;
There is no doubt here. C is final, but internal members should be able to modify it. Why.

Expand add: First of all, the bottom of the ArrayList implementation is the array used:

public class Arraylist<e> extends abstractlist<e>
implements List<e>, Randomaccess, Cloneable, Java.io.Serializable
{
private static final long serialversionuid = 8683452581122892189L;
private static final int default_capacity = ten;
private static final object[] Empty_elementdata = {};
Private transient object[] elementdata ...
		.
		And so on
}

So for final collection<? Extends e> C Finalc Why not modify the feeling of doubt. In fact, the use of proxy mode here is to enhance the Add method, look at the Add method to know:

        Public boolean Add (E e) {
            throw new unsupportedoperationexception ();
        }

The answer is natural.

However, it should be noted that if we modify the original list in our code, then Unmodifiablecollection will also be modified, and the view here is similar to the view of the database.


Next look at the method:

Synchronizedmap (map<k,v> m)

Returns a synchronized map. Returns the synchronization (thread-safe) mappings supported by the specified mapping. To ensure sequential access, all access to the underlying implementation map must be completed through the returned mapping.

First take a look at HashMap-safe:

Package com.daxin.collections;
Import Java.util.HashMap;

Import Java.util.Map;

	Class Service {private map map = null;
		Public Service (map map) {super ();
	This.map = map;
	Public Map Getmap () {return map;
	public void Setmap (map map) {this.map = map;

	} class Threada extends Thread {private service service;
		Public Threada (Service service) {super ();
	This.service = Service;

		@Override public void Run () {for (int i = 1; I <= 5; i++) {Service.getmap ()]. put (i + "", I + "");

	}} class Threadb extends Thread {private service service;
		Public threadb (Service service) {super ();
	This.service = Service;

		@Override public void Run () {for (int i = 1; I <= 5; i++) {Service.getmap ()]. put (i + "", I + "AAA"); }} public class Main2 {public static void main (string[] args) throws Exception {Map map=new Hashmap<stri
		Ng,string> ();
		Service service = new service (map); Threada a = new Threada (servICE);

		THREADB B = new threadb (service);
		A.start ();
		B.start ();
		A.join ();

		B.join ();
		System.out.println (Service.getmap ()); Output {3=3aaa, 2=2aaa, 1=1aaa, 5=5AAA, 4=4aaa} or {3=3aaa, 2=2aaa, 1=1,//5=5AAA, 4=4AAA} The results of multiple runs are inconsistent, and two threads alternate execution results in multiple output inconsistencies.
 Thread safety issue/thread safe See Main3 source}


Improved version, thread safe version:


Package com.daxin.collections;

Import java.util.Collections;
Import Java.util.HashMap;
Import Java.util.Map;

public class Main3 {public
	static void Main (string[] args) throws Exception {

		Map MAP=COLLECTIONS.SYNCHRONIZEDMA P (new hashmap<string,string> ());
		
		
		Service service = new service (map);
		Threada a = new Threada (service);
		THREADB B = new threadb (service);

		A.start ();
		B.start ();
		A.join ();
		B.join ();

		System.out.println (Service.getmap ());
		
		Output: {3=3aaa, 2=2aaa, 1=1aaa, 5=5AAA, 4=4aaa} or {3=3, 2=2, 1=1, 5=5, 4=4} Two results, this is mainly to see
		//Who first got the lock who got the lock, the output is the final lock results.
		//No two threads are alternately executing

	}

}

Next look at the Synchronizedmap method source code:

    public static <K,V> map<k,v> Synchronizedmap (map<k,v> m) {return
        new synchronizedmap<> (m) ;
    }

Then look at the Synchronizedmap construction method (Synchronizedmap is a static internal class of collections):

private static Class Synchronizedmap<k, V> implements Map<k, V>, Serializable {
	private static final long Serialversionuid = 1978198479659022715L;

	Private final map<k, v> m; Backing Map
	Final object mutex;//object on which to synchronize, synchronized lock object

synchronizedmap (map<k,v> m) {
  if (m==null)
        throw new NullPointerException ();
    THIS.M = m;
    Mutex = this;//Sets the mutex as the current object and other constructors view it yourself

	... And so on
}

Then look at Synchronizedmap's put and other common methods source code:

  Public V-Put (K key, v. value) {
            synchronized (mutex) {return M.put (key, value);}
        }
        Public V-Remove (Object key) {
            synchronized (mutex) {return m.remove (key);
        }
        public void Putall (map<? extends K,? extends V> Map) {
            synchronized (mutex) {M.putall (MAP);}
        }
Each time the operation of the Synchronizedmap is actually a lock on the mutex object, using the synchronized code block implementation.


Looking at the Java.util.Collections.synchronizedSet (set<string>) method, the principle is similar:

Creates a Synchronizedset return (Synchronizedset inherits the Synchronizedcollection class, Synchronizedcollection implements code block synchronization for members of the member mutex).

Method Java.util.Collections.synchronizedList (List<string>) Implementation principle is also as above.









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.