[Valid Java] 12. Avoid excessive synchronization.

Source: Internet
Author: User

[Valid Java] 12. Avoid excessive synchronization.

Here is an auxiliary basic class

Package cn. xf. cp. ch02.item16; import java. util. collection; import java. util. iterator; import java. util. set; public class ForwardingSet <E> implements Set <E> {/*** this class is used as the forwarding class, internally, set is used as a component by means of combination */private final Set <E> s; public ForwardingSet (Set <E> s) {this. s = s ;}@ Override public int size () {return s. size () ;}@ Override public boolean isEmpty () {return s. isEmpty () ;}@ Override public boolean contai Ns (Object o) {return s. contains (o) ;}@ Override public Iterator <E> iterator () {return s. iterator () ;}@ Override public Object [] toArray () {return s. toArray () ;}@ Override public <T> T [] toArray (T [] a) {return s. toArray (a) ;}@ Override public boolean add (E e) {return s. add (e) ;}@ Override public boolean remove (Object o) {return s. remove (o) ;}@ Override public boolean containsAll (Collection <?> C) {return s. containsAll (c) ;}@ Override public boolean addAll (Collection <? Extends E> c) {return s. addAll (c) ;}@ Override public boolean retainAll (Collection <?> C) {return s. retainAll (c) ;}@ Override public boolean removeAll (Collection <?> C) {return s. removeAll (c) ;}@ Override public void clear () {s. clear ();}}

 

Then, use a class to enable the class to be registered by the observer.

Package cn. xf. cp. ch02.item67; import java. util. arrayList; import java. util. collection; import java. util. list; import java. util. set; import cn. xf. cp. ch02.item16. forwardingSet; public class ObservableSet <E> extends ForwardingSet <E> {public ObservableSet (Set <E> s) {super (s );} private final List <SetObserver <E> observers = new ArrayList <SetObserver <E> (); public void addObserver (SetObserver <E> observer ){ Synchronized (observers) {observers. add (observer) ;}} public boolean removeObserver (SetObserver <E> observer) {synchronized (observers) {return observers. remove (observer) ;}}// This method is the culprit private void your yelementadded (E element) {synchronized (observers) {for (SetObserver <E> observer: observers) observer. added (this, element) ;}} private void extends yelementadded2 (E element) {List <SetObserver <E> snapshot = null; synchronized (observers) {// take a snapshot here, in this way, we do not need to lock the original set during traversal. snapshot = new ArrayList <SetObserver <E> (observers) ;}for (SetObserver <E> observer: snapshot) observer. added (this, element) ;}@ Override public boolean add (E e) {// call the parent class function to add it to the set boolean added = super. add (e); if (added) {// added successfully. The observer saves the registered object notifyElementAdded (e) ;}return added ;}@ Override public Boolean addAll (Collection <? Extends E> c) {boolean result = false; for (E element: c) {// performs or operations, as long as one add operation is successfully added, true result | = add (element) ;}return result ;}}

It can be noted that there are already two methods in this class.

Observer:

Package cn. xf. cp. ch02.item67; public interface SetObserver <E> {/*** when an element is added to an ObservableSet object, call * @ param set * @ param element */void added (ObservableSet <E> set, E element );}

 

Test:

Package cn. xf. cp. ch02.item67; import java. util. hashSet; import java. util. concurrent. executionException; import java. util. concurrent. executorService; import java. util. concurrent. executors; public class Test {@ org. junit. test public void test () {// create an observed object ObservableSet <Integer> set = new ObservableSet <Integer> (new HashSet <Integer> ()); // Add an observer set. addObserver (new SetObserver <Integer> () {public void Dded (ObservableSet <Integer> s, Integer e) {System. out. println (e) ;}}); for (int I = 0; I <100; I ++) set. add (I) ;}@ org. junit. test public void test2 () {ObservableSet <Integer> set = new ObservableSet <Integer> (new HashSet <Integer> (); set. addObserver (new SetObserver <Integer> () {public void added (ObservableSet <Integer> s, Integer e) {System. out. println (e); if (e = 23) // to 23, we cancel this observer, but an exception occurs because When traversing the list iteratively, we modified the list by ourselves. This is invalid s. removeObserver (this) ;}}); for (int I = 0; I <100; I ++) set. add (I);}/*** how to cancel the observer ???? * We use another thread to delete the observer at 23 */@ org. junit. test public void test3 () {ObservableSet <Integer> set = new ObservableSet <Integer> (new HashSet <Integer> (); set. addObserver (new SetObserver <Integer> () {@ Override public void added (final ObservableSet <Integer> set, Integer element) {System. out. println (element); // if it is 23 if (element = 23) {// thread pool, create a thread pool for a single thread. if the current thread is suddenly interrupted during task execution, A new thread will be created to replace it to continue executing the task ExecutorService executor = Executors. newSingleThreadExecutor (); final SetObserver <Integer> observer = this; try {executor. submit (new Runnable () {@ Override public void run () {// here the set will be deadlocked. removeObserver (observer );}}). get ();} catch (InterruptedException e) {e. printStackTrace ();} catch (ExecutionException e) {e. printStackTrace ();} finally {executor. shutdown () ;}}}); for (int I = 0; I <100; I ++) set. add (I );}}

 

 

Result:

 

Test 2

 

 

 

 

An exception is thrown here. Why is the reason already written in the class?

 

Test 3

This will cause deadlocks.

 

 

Let's avoid locking the internal set of external calls, but create a snapshot and lock the snapshot.

Key point: it is the external call function. It is best not to enter the synchronization zone. In short, the synchronization zone should be operated internally as much as possible. The synchronization zone should do as little work as possible to obtain the lock, process the data, and release the lock, all completed internally

 

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.