Java concurrent programming practical study note object combination and basic construction module

Source: Internet
Author: User

Java concurrent programming practical study note object combination and basic construction module
Chapter 4 object combination 4.1 Build a secure Class 4.2 instance closed

@ThreadSafepublic class PersonSet {    @GuardedBy("this") private final Set<Person> mySet = new HashSet<Person>();    public synchronized void addPerson(Person p) {        mySet.add(p);    }    public synchronized boolean containsPerson(Person p) {        return mySet.contains(p);    }    interface Person {    }}

 

The object myset of the personset is encapsulated, but the security of the person is unknown. It is also called the java monitor mode to use a private lock to protect the object.
public class PrivateLock {    private final Object myLock = new Object();    @GuardedBy("myLock") Widget widget;    void someMethod() {        synchronized (myLock) {            // Access or modify the state of widget        }    }}

 

4.3 The immutable thread-safe delegation domain is thread-safe. It can be freely shared and released to the Application Thread-Safe Container to encapsulate the state domain in the class to achieve thread-safe, implementing the class security *** to other classes at the underlying layer is called thread security delegation. However, if multiple mutually dependent composite objects exist, the lock must also be used for security. 4.4 Add a function to the existing thread security class 1) Add a method to the original Class 2) extend the original class through inheritance 3) Add a function client lock through a helper class:
@ NotThreadSafeclass BadListHelper <E> {public List <E> list = Collections. synchronizedList (new ArrayList <E> (); public synchronized boolean putIfAbsent (E x) {// the built-in lock is a different boolean absent = for the client! List. contains (x); if (absent) list. add (x); return absent ;}@ ThreadSafeclass GoodListHelper <E >{ public List <E> list = Collections. synchronizedList (new ArrayList <E> (); public boolean putIfAbsent (E x) {synchronized (list) {// list object lock is the same boolean absent = for each client! List. contains (x); if (absent) list. add (x); return absent ;}}}

 

Who calls the first built-in class above is combined with WHO:
@ThreadSafepublic class ImprovedList<T> implements List<T> {    private final List<T> list;    /**     * PRE: list argument is thread-safe.     */    public ImprovedList(List<T> list) { this.list = list; }    public synchronized boolean putIfAbsent(T x) {        boolean contains = list.contains(x);        if (contains)            list.add(x);        return !contains;    }

 

Introduce list as a member variable. The built-in lock is the object of this class. Chapter 5 basic building module 5.1 synchronization container class: Vector Hashtable is encapsulated to synchronize each public method, so that only one thread can access the container status at a time. All accesses to the container status are serialized, with low efficiency. Synchronization containers are thread-safe, but you need to lock yourself to perform complex compound operations, such as iterations. If another thread modifies the container during iteration, an error occurs. This problem is not solved when designing synchronization containers. Therefore, you still need to lock yourself to avoid exceptions. However, this will make the efficiency very low, because other threads are not allowed to access during the entire iteration, the improvement is to clone the container. Beware of another hidden iteration: "helloworld" + set; The toString () function of the set will be called to execute the iteration in the function, and the hashcode and equals methods of the container will also execute the iteration. 5.2 concurrent container: concurrentHashMap CopeOnWriteArrayListconcurrentHashMap: not to put every method in the same lock for synchronization and only one thread can access the container at the same time, 20. More fine-grained locks are used to achieve greater sharing. The iterator provided by it does not throw an exception, so it does not need to be locked during the iteration process. CopeOnWriteArrayList: used to replace the synchronization list. No locks and replication are required during iteration. At each modification, the underlying array is copied. After the modification, a new container version is released. 5.3 blocking queue and producer-consumer mode blockingQueue5.4 blocking method and interrupt method when a method that throws an interruptedException exception is called in the code, it becomes a blocking method, when an interruptedException exception is caught, the most sensible choice is to pass it to the caller, that is, to throw an interruptedException exception again. If an exception cannot be thrown, the interrupt method of the thread is called to resume the interruption. The upper-Layer Code will see that an interruption is triggered. For example:
public class TaskRunnable implements Runnable {    BlockingQueue<Task> queue;    public void run() {        try {            processTask(queue.take());        } catch (InterruptedException e) {            // restore interrupted status            Thread.currentThread().interrupt();        }    }    void processTask(Task task) {        // Handle the task    }    interface Task {    }}

 

5.5 synchronization tool lock: countDownLatchfutureTask: asynchronous event semaphore: counting semaphore fence: blocking is used to wait for events, and the fence is used to wait for processes. Repeatable fence reset for Reuse

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.