Java Multithreading--Synchronization (ii)

Source: Internet
Author: User

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

    • Locks are used to protect code fragments, and only one thread can execute the protected code at any time.
    • Locks can manage threads that attempt to enter a protected code segment.
    • A lock can have one or more related conditional objects.
    • Each conditional object manages threads that have entered a protected code segment but are not yet able to run.
Synchronized keywords


Each object in Java has an internal lock, and if a method is declared with the Synchronized keyword, the lock on the object will protect the entire method. An internal object lock has only one related condition, and the wait method adds a thread to the wait set, and the Notifyall/notify method unlocks the blocking state of the waiting thread.

Modify the Bank class using synchronized:

/** * @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 (a         Ccounts[from] < amount) {wait ();//Put the thread into the waiting set of the condition} System.out.print (Thread.CurrentThread ());        Accounts[from]-= amount;        System.out.printf ("Transfer amount:%10.2f Transfer account:%d transferred to account:%d", amount, from, to);        Accounts[to] + = amount;        System.out.printf ("Final amount:%10.2f%n", gettotalbalance ()); Notifyall ();        The blocking state of all threads in the wait set for the condition is lifted} 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 a little more concise. Each object has an internal lock, and the lock has an internal condition that is used by the lock to manage those threads that attempt to enter the Synchronized method, and the condition is used to manage those threads that call wait.


Limitations of internal locks and conditions
    • Cannot interrupt a thread that is attempting to acquire a lock
    • Cannot set timeout when attempting to acquire lock
    • Each lock has only a single condition and may not be enough

Synchronous blocking


Each object has a lock. A thread can obtain a lock by invoking a synchronous method. There is another way to get the lock by entering a synchronous block.

Get the lock on the obj object:

        Synchronized (obj) {work            code        }

Volatile domain


Sometimes it is too expensive to use synchronization just to read and write to one or two instance domains. The volatile keyword provides a lock-free mechanism for synchronizing access to an instance domain. If you declare a domain to be volatile, then the compiler and the virtual machine know that the domain is likely to be updated concurrently 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 the volatile modifier is used. There is also a situation where you can safely access a shared domain when the domain is declared final.


Dead lock


It is possible that all threads are blocked because each thread waits for more money to be deposited. Such a state is called a deadlock. Note there is also a situation that can easily lead to deadlocks: When the waiting thread is unblocked, if only one line is threads unlocked, not all of the waiting threads. (signal or notify) it is just a line threads unlocked, and it is likely that it will choose a thread that cannot continue to run, so that a deadlock can occur.


Read/write Lock


Necessary steps for using read/write locks:

    • Constructs a Reentrantreadwritelock object:
    Private Reentrantreadwritelock RWL = new Reentrantreadwritelock ();

    • Get read and Write locks:
    Private final Reentrantreadwritelock rwl       = new Reentrantreadwritelock ();    Private final Lock                   readlock  = Rwl.readlock ();    Private final Lock                   Writelock = Rwl.writelock ();

    • Read lock for all fetch methods:

    Public double gettotalbalance () {        readlock.lock ();        try{...        } finally{            Readlock.unlock ();        }    }

    • Write locks on all modified methods:
    public void Transfer () {        writelock.lock ();        try{...        } finally{            Writelock.unlock ();        }    }


Java Multithreading--Synchronization (ii)

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.