Java Multithreading thread Security Implementation __java

Source: Internet
Author: User

Thread safety is to ensure the high consistency and accuracy of data, but not necessarily lock is thread security, as long as there is no variable in the code, the thread between the interaction, is thread-safe.
To understand thread safety, you can first look at how thread insecurity is a phenomenon.

public class Treadnosafedemo {public
    static void Main (string[] args) {
       new Threadnosafetest (). Start ();
       New Threadnosafetest (). Start ();
       New Threadnosafetest (). Start ();
       New Threadnosafetest (). Start ();
    }
}

Class Threadnosafetest extends thread{
    private int num=5;
    @Override public
    Void Run () {
        try {
            thread.sleep ()
        } catch (Interruptedexception e) {
            E.printstacktrace ();
        }
        System.out.println (Thread.CurrentThread (). GetName () + "..." + (--num));} (+).


From the results of the operation can be seen: –num output is not what we think of 4 3 2 1, this is the thread of the unsafe phenomenon.

How can you achieve thread safety? What are the mechanisms that Java provides us with?
There are roughly three ways to implement thread safety: it does not apply to singleton schemas, but to multiple instances. Use lock mechanism synchronized, lock mode. Use the class library below Java.util.concurrent.

The following is an introduction to the specific methods:
implicit locks (thread synchronization synchronized)
There are two ways to thread synchronization synchronized, one is on the synchronization method, the other is in the synchronized code block.
Sync Method:

Public synchronized void Methodtest () {
        try {
            thread.sleep ()
        } catch (Interruptedexception e) {
            E.printstacktrace ();
        }
            System.out.println (Thread.CurrentThread (). GetName () + "..." + (--num)); "+"..
    

Synchronizing code blocks

public void Methodtest () {
        try {
            thread.sleep ()
        } catch (Interruptedexception e) {
            E.printstacktrace ();
        }
        Synchronized (object) {
            System.out.println (Thread.CurrentThread (). GetName () + ".... ..." + (--num));
        }
    }

show Lock and Reentrantlock
Lock and unlock are displayed.
The main methods of the Lock interface (Java.util.concurrent.locks.Lock) are:

Reentrantlock is the implementation class for lock and is a mutex.
Reentrantlock implementations are more scalable than synchronized implementations under competitive conditions, which means that when many threads compete for the same lock, the reentrantlock throughput is usually better than the synchronized.
Reentrantlock is the most frequently used method block lock.
How to use:

Class reentrantlocktest{
    private final Reentrantlock reentrantlock=new Reentrantlock ();
    public void Methodtest () {
        reentrantlock.lock ();
        try {//................... ...
        } catch (Exception e) {

        }
        reentrantlock.unlock ();
    }
}

Show lock Readwritelock and Reentrantreadwritelock
Readwritelock is also an interface that provides an operating mechanism for the Readlock and Writelock two locks, one for read-only operations and another for write operations. As long as there is no writer, the read lock can be persisted by multiple reader threads at the same time. The write lock is exclusive. Read-write locks use a scenario where a shared resource is read-only with a small amount of write operations. (Read is not mutually exclusive, read and write mutually exclusive, write mutually exclusive;).
The difference between Reentrantreadwritelock and Reentrantlock: Reentrantreadwritelock is a complex extension of reentrantlock, Reentrantreadwritelock can implement a mechanism for reading and writing a separate lock in a method, while Reentrantlock lock unlock is only a mechanism.

Show Lock Stampedlock
Stampedlock can greatly increase the throughput of the program's read locks. In the case of a large number of read and few writes, optimistic read locks can greatly increase throughput and reduce hunger in this case.

Viewing: Comparison of synchronized, Reentrantlock, Reentrantreadwritelock and Stampedlock

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.