Java multithreading-synchronization (2)

Source: Internet
Author: User

Java multithreading-synchronization (2)

In the previous article, we summarized how to use the Lock and Condition objects. Let's first summarize the key points about locks and conditions:

The lock is used to protect code snippets. At any time, only one thread can execute the protected code. The lock can manage threads that attempt to enter protected code segments.
A lock can have one or more related condition objects. Each condition object manages the threads that have entered the protected code segment but cannot run. Synchronized keyword


Each object in Java has an internal lock. If a method is declared with the synchronized keyword, the object lock will protect the entire method. The internal object lock has only one related condition. The wait method adds a thread to the waiting set, and the yyall/notify method unblocks the waiting thread.

Use synchronized to modify the Bank class:

/*** @ Author XzZhao */public class Bank {private final double [] accounts; public Bank (int n, double initialBalance) {accounts = new double [n]; for (int I = 0; I <accounts. length; I ++) {accounts [I] = initialBalance;} public synchronized void transfer (int from, int to, double amount) throws InterruptedException {while (accounts [from] <amount) {wait (); // puts the thread in the waiting set of conditions} System. out. print (Thread. currentThread (); accounts [from]-= amount; System. out. printf ("transfer amount: % 10.2f transfer account: % d", amount, from, to); accounts [to] + = amount; System. out. printf ("last amount: % 10.2f % n", getTotalBalance (); policyall (); // cancel the blocking status of all threads in the waiting set for this condition} public synchronized double getTotalBalance () {double sum = 0; for (double a: accounts) {sum + = a;} return sum;} public int size () {return accounts. length ;}}

Writing code with the synchronized keyword is concise. Each object has an internal lock and the lock has an internal condition. The lock is used to manage the threads that attempt to enter the synchronized method, and the conditions are used to manage the threads that call wait.


Limitations of internal locks and conditions cannot interrupt a thread attempting to obtain the lock. when trying to obtain the lock, it cannot be set to time-out. Each lock has only one condition, which may not be enough.
Synchronization Blocking


Each object has a lock. The thread can obtain the lock by calling the synchronization method. There is another way to get the lock by entering a synchronization blocking.

Get the obj object lock:

        synchronized (obj) {            work code        }

Volatile domain


Sometimes, it seems overhead to use synchronization only to read and write one or two instance domains. The volatile keyword provides a lock-free mechanism for Synchronous access to the instance domain. If you declare a domain as volatile, the compiler and virtual machine will know that this domain may be concurrently updated by another thread.

For example:

    private volatile boolean result;    public boolean isResult() {        return result;    }    public void setResult(boolean result) {        this.result = result;    }

Final variable


A domain cannot be safely read from multiple threads unless the lock or volatile modifier is used. Another scenario is to securely access a shared domain when the domain is declared as final.


Deadlock


All threads may be blocked because each thread needs to wait for more money to be saved. Such a state is called a deadlock. Note that there is also a situation that can easily lead to deadlocks: that is, when the blocking status of the waiting thread is lifted, if only one thread is unlocked, rather than all waiting threads. (Signal or notify) It is only unlocked for a thread, and it is likely to choose a thread that cannot continue running, so that a deadlock will occur.


Read/write lock


Steps to use a read/write lock:

Construct a ReentrantReadWriteLock object:
    private ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();

Get the Read and Write locks:
    private final ReentrantReadWriteLock rwl       = new ReentrantReadWriteLock();    private final Lock                   readLock  = rwl.readLock();    private final Lock                   writeLock = rwl.writeLock();

Apply a read lock to all obtaining methods:

    public double getTotalBalance(){        readLock.lock();        try{            ...        }finally{            readLock.unlock();        }    }

Apply a write lock to all modification methods:
    public void transfer(){        writeLock.lock();        try{            ...        }finally{            writeLock.unlock();        }    }


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.