Java multithreaded thread synchronization

Source: Internet
Author: User
Tags volatile

If you are writing a variable, it may be next read by another thread, or you are reading a variable that has been written by another thread for the last time, then you need to use synchronization, and the read-write thread must be synchronized with the same monitor lock. --brain Synchronization Rules

Synchronized

    1. All objects automatically contain a single lock, which is locked when any of the synchronized methods of an object are called.
    2. For a particular object, all synchronized methods share the same lock. So when a thread accesses an synchronized method of an object, any synchronized methods that other threads access the object will be blocked.
    3. A task can obtain an object lock multiple times, such as when a method of an object is called, and another method is called. The JVM is responsible for tracking the number of times an object is locked, which is also the reentrant nature of the lock, which can cause a deadlock.
    4. Each class also has a lock, each class is a class object, and the synchronized static method prevents concurrent access to the static data
    5. When using concurrency, it is a good idea to set the field to private to prevent the thread from accessing the field directly.

Can be re-entered lock Reentrantlock

An explicit lock is defined in the Java.util.concurrent.locks package that requires an explicit creation, locking, and deallocation. Explicit lock locks are more cumbersome to use than the Synchronized keyword, and are more likely to go wrong when used, but with more powerful features. The locks package contains two types of lock Reentrantlock and Reentrantreadwritelock.

    1. Reentrantreadwritelock, read some of the blog to understand the next. The thread enters the read lock precondition, (a) there is no other thread's write lock, (b) No write request or write request, but the calling thread and the thread holding the lock are the same, the thread enters the write lock precondition, (a) there is no other thread's read lock, (b) There is no other thread's write lock.
    2. Reentrantlock has two constructs, Reentrantlock (Boolean Fair) fair to True to tell the created lock to be a fair lock, without transmitting the fair parameter to create an unfair lock. An unfair lock is a direct fetch lock, no maintenance waiting queue, and a fair lock still needs to check whether the current thread is the first one to wait for the queue.
 Public classLocktest {Private intCurrent = 0; PrivateLock lock =NewReentrantlock ();  Public intNext () {//Lock.lock ();        BooleanFlag =Lock.trylock (); if(flag) {Try{                ++Current ;                Thread.yield (); ++Current ; returnCurrent ; }finally{lock.unlock (); }        }Else{System.out.println ("Locked"); return-1; }    }}

The display lock can be used to try to acquire the lock, which is more flexible than the synchronized keyword. Trylock (long timeout, timeunit unit) can also set the time you are waiting to acquire a lock. Because lock locks are more likely to go wrong, use the Synchronized keyword unless you are troubleshooting a particular problem.

Volatile

You can use the volatile keyword to make the assignment and return operations of a primitive type variable that you define as an atomic operation.

Volatile can be a declared field with visibility. Visibility means that whenever you write to a field, all of the read operations can see the change. Because a thread's modification of a field may not be directly reflected in memory, other threads will not get the most recent value.

The volatile keyword should be used with caution, and the Synchronized keyword is preferred when thread synchronization is required.

Atomic class

Java SE5 provides special atomic variable classes such as Atomicinteger, Atomiclong, Atomicreference, and so on. These classes are updated with atomic conditions in the form of a Boolean compareandset (int expect, int update). These atomic classes have basic get, set operations, which are used to get and set values.

The atomic class is designed to be used to build classes in java.util.concurrent, and it is safer to use regular programming or locks, but these atoms are useful when it comes to performance tuning.

 Public classAtomicitytestImplementsRunnable { Public Static voidMain (string[] args) {//TODO auto-generated Method Stub        NewTimer (). Schedule (NewTimerTask () {@Override Public voidrun () {//TODO auto-generated Method StubSystem.err.println ("aborting"); System.exit (0); }        }, 5000); Executorservice exec=Executors.newcachedthreadpool (); Atomicitytest at=Newatomicitytest ();                Exec.execute (at);  while(true){            intval =At.getvalue (); if(val% 2! = 0) {System.out.println (val); System.exit (0); }        }    }        PrivateAtomicinteger i =NewAtomicinteger (0);  Public intGetValue () {returnI.get (); }        Private voidevenincrement () {I.addandget (2);    System.out.println (i); } @Override Public voidrun () { while(true) evenincrement (); }}

Synchronizing on critical sections and other objects

Sometimes we just want a part of the code not to be accessed by multiple threads at the same time, and this type of code block is called the critical section. Critical sections can be created using the Synchronized keyword.

Synchronized (SyncObject) {//critical section Code}

When a thread enters a critical section code block, it must obtain a lock on the SyncObject object. It is important to note that SyncObject can be either the object itself this or other objects. In introducing the Synchronized keyword, all objects contain a lock, and the critical section is implemented by object lock. This allows multiple threads to enter the same object at the same time, as long as the object is accessed by a code block that uses a different object lock.

ThreadLocal

Threadlocal prevents conflicts of shared resources in multiple threads by eliminating the sharing of variables. Threadlocal creates different stores for each different thread that uses the same variable. Threadlocal objects are usually stored as static fields. The following code, which is equivalent to each thread, has an integer ID set for it.

 Public classThreadlocaltest { Public StaticThreadlocal<integer> value =NewThreadlocal<integer>(){        protected synchronizedInteger InitialValue () {return100;        }    };  Public Static voidMain (string[] args) {//TODO auto-generated Method Stub        NewTimer (). Schedule (NewTimerTask () {@Override Public voidrun () {//TODO auto-generated Method StubSystem.exit (0); }        }, 5000); Executorservice exec=Executors.newcachedthreadpool ();  for(inti=0; i<10; ++i) {Exec.execute (NewAccesor (Value.get ()));    } exec.shutdown (); }}classAccesorImplementsRunnable {Private intID;  Publicaccesor (Integer id) { This. ID =Id.intvalue (); System.out.println ("Init value:" + This. ID); }         Public voidrun () { while(true) id++; }}

Java multithreaded thread synchronization

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.