"Effective Java" 12, avoid over-synchronization

Source: Internet
Author: User

Here is an auxiliary base class

 Packagecn.xf.cp.ch02.item16;Importjava.util.Collection;ImportJava.util.Iterator;ImportJava.util.Set; Public classForwardingset<e>ImplementsSet<e>{        /*** This class acts as a forwarding class and internally uses the set as a component in a composite way*/    Private FinalSet<e>s;  PublicForwardingset (set<e>s) { This. S =s; } @Override Public intsize () {returns.size (); } @Override Public BooleanIsEmpty () {returnS.isempty (); } @Override Public Booleancontains (Object o) {returns.contains (o); } @Override PublicIterator<e>iterator () {returnS.iterator (); } @Override Publicobject[] ToArray () {returnS.toarray (); } @Override Public<T>t[] ToArray (t[] a) {returnS.toarray (a); } @Override Public BooleanAdd (e e) {returnS.add (e); } @Override Public BooleanRemove (Object o) {returnS.remove (o); } @Override Public BooleanContainsall (collection<?>c) {returnS.containsall (c); } @Override Public BooleanAddAll (collection<?extendsE>c) {returnS.addall (c); } @Override Public BooleanRetainall (collection<?>c) {returnS.retainall (c); } @Override Public BooleanRemoveAll (collection<?>c) {returnS.removeall (c); } @Override Public voidClear () {s.clear (); }}

Then use a class to enable the class to be registered by the Observer

 Packagecn.xf.cp.ch02.item67;Importjava.util.ArrayList;Importjava.util.Collection;Importjava.util.List;ImportJava.util.Set;ImportCn.xf.cp.ch02.item16.ForwardingSet; Public classObservableset<e>extendsForwardingset<e>{     PublicObservableset (set<e>s) {Super(s); }        Private FinalList<setobserver<e>> observers =NewArraylist<setobserver<e>>();  Public voidAddobserver (setobserver<e>observer) {        synchronized(observers) {OBSERVERS.ADD (Observer); }    }     Public BooleanRemoveobserver (setobserver<e>observer) {        synchronized(observers) {returnOBSERVERS.REMOVE (Observer); }    }    //This method is the culprit    Private voidnotifyelementadded (E element) {synchronized(observers) { for(setobserver<e>observer:observers) observer.added ( This, Element); }    }        Private voidNotifyElementAdded2 (E Element) {List<SetObserver<E>> snapshot =NULL; synchronized(observers) {//take a snapshot here so that we don't have to lock the original set when we traverse it.snapshot =NewArraylist<setobserver<e>>(observers); }         for(setobserver<e>observer:snapshot) observer.added ( This, Element); } @Override Public BooleanAdd (e e) {//Call the parent class function to add to the collection        BooleanAdded =Super. Add (e); if(added) {//added successfully, Viewer saves registered objectnotifyelementadded (e); }                returnadded; } @Override Public BooleanAddAll (collection<?extendsE>c) {Booleanresult =false;  for(E element:c) {//to do or operate, as long as an add is successful, result is trueResult |=Add (Element); }        returnresult; }}

Notice that there is already a place in this class that has two methods, which will later

Observed by:

 Package cn.xf.cp.ch02.item67;  Public Interface Setobserver<e>{    /**     * When an element is added to the Observableset object, the call      @param  set     @param  element     *    /void added ( Observableset<e> Set, E Element);}

Test:

 Packagecn.xf.cp.ch02.item67;ImportJava.util.HashSet;Importjava.util.concurrent.ExecutionException;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors; Public classtest{@org. Junit.test Public voidTest () {//create an object to be observedObservableset<integer> set =NewObservableset<integer> (NewHashset<integer>()); //Add an observerSet.addobserver (NewSetobserver<integer>()        {             Public voidAdded (observableset<integer>s, Integer e)            {System.out.println (e);        }        });  for(inti = 0; I < 100; i++) Set.add (i); } @org. junit.test Public voidtest2 () {Observableset<Integer> set =NewObservableset<integer> (NewHashset<integer>()); Set.addobserver (NewSetobserver<integer>()        {             Public voidAdded (observableset<integer>s, Integer e)                {System.out.println (e); if(E = = 23)//by 23, we cancel the observer, but we get an exception because we modify the list ourselves when iterating through the list, which is illegal.S.removeobserver ( This);        }        });  for(inti = 0; I < 100; i++) Set.add (i); }        /*** So how to cancel the Observer???? * We use another thread to delete this viewer at 23*/@org. Junit.test Public voidtest3 () {Observableset<Integer> set =NewObservableset<integer> (NewHashset<integer>()); Set.addobserver (NewSetobserver<integer>() {@Override Public voidAddedFinalObservableset<integer>set, Integer Element)                {System.out.println (element); //if it is                if(element = = 23)                {                    //Thread pool, which creates a thread pool of a single threads, creates a new thread instead of executing the task if the current thread breaks abruptly when the task is executedExecutorservice executor =Executors.newsinglethreadexecutor (); Finalsetobserver<integer> Observer = This; Try{executor.submit (NewRunnable () {@Override Public voidrun () {//There's going to be a deadlock.Set.removeobserver (Observer);                    }}). get (); }                    Catch(interruptedexception e) {e.printstacktrace (); }                    Catch(executionexception e) {e.printstacktrace (); }                    finally{executor.shutdown ();                }                }            }        });  for(inti = 0; I < 100; i++) Set.add (i); }}

Results:

Test 2

Here will throw an exception, why, the reason has been written in the class

Test 3

This will cause a deadlock, to use

Let the internal collection of external calls avoid locking, but instead create a snapshot and then lock the snapshot

Point: Is the external call function, it is best not to enter the synchronization zone, in short, the synchronization area as far as possible in the internal operation, synchronization area as little as possible, to obtain locks, processing data, release locks, are completed in-house

"Effective Java" 12, avoid over-synchronization

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.