synchronized and ReentrantLock What is the difference? Some people say that synchronized slowest, words fly it?

Typical answer

synchronized synchronization mechanism is built-in java, so it was called instrinisc Locking (intrinsic lock), which provides mutual exclusion semantics and visibility, when a current thread has acquired the lock, other threads can only wait attempts to acquire or obstruction there.

In java5 past, the only means of synchronization are synchronized, in code, can be used to modify synchronized method may also be used on a particular block of code, the method essentially equivalent to the method sychronized all statements wrap synchronized block.

Of ReentrantLock, usually translated into reentry lock, the lock is provided java5 implemented, its semantics synchronized and substantially identical. Re-entry lock code directly by calling lock () method to get the code to write more flexible. At the same time it provides a lot of real ReentrantLock

Methods can be synchronized to provide many details do not control, you can control such as fairness, that is fairness, or the use of defined conditions. However, coding also need to pay attention, you must explicitly call the unlock () method releases, otherwise would have been holding the lock.

ReentrantLock performance synchronized and can not be generalized, earlier versions synchronized in many scenes performance difference between the larger, more improvements made in subsequent releases, the performance may be superior in low ReentrantLock competition scene.

Continued to expand knowledge for understanding the lock down

First, understand what is thread safe

Definition: security thread is the concept of the correctness of the next multi-threaded environment, that is, to ensure the sharing of multi-threaded environment, you can modify the correctness of the state, where the state actually can be seen as a reflection of the data in the program.

From another angle, if the state is not shared, or is not modifiable, thread-safety problem does not exist, then we know that two thread-safe way to ensure that:

  • Package: The package we can hide the internal state of the object, protected.
  • Immutable: defined variables or objects is final, java native language there is no real sense of the immutable.

The need to ensure security thread a few basic features:

  • Atomicity, it simply is not related to operations other way disturb the thread is generally achieved by synchronizing mechanism.
  • Visibility is one thread to modify a shared variable, the state can immediately know the other thread, the thread is usually interpreted as the local state reflected in the main memory, volatile is responsible for ensuring visibility.
  • Ordering, a serial semantics, to avoid rearrangement instruction threads guaranteed.

A little hard to understand, look at the code, the demand is reflected in the analysis where atoms. This example was then extracted twice by comparing values ​​to simulate the operation of two of the shared state.

You can compile and execute, we can see, only the low two concurrent threads, it is very easy to run into former and latter case is not equal. This is because, in the course of the two values, the other threads may have modified shareState.

public class ThreadSafeSample {

    public int shareState;
    public void nonSafeAction(){
        while(shareState<100000){
                int former = shareState++;
                int latter = shareState;
                if(former !=latter - 1){
                    System.out.println("Observed data race,former is"+former+","+"latter is"+latter);
                }

        }
    }
    public static void main(String[] args) throws InterruptedException{
        final ThreadSafeSample sample = new ThreadSafeSample();
        Thread threadA = new Thread(){
            public void run(){
                sample.nonSafeAction();
            }
        };
        
        Thread threadB = new Thread(){
            public void run(){
                sample.nonSafeAction();
            }
        };
        
        threadA.start();
        threadB.start();
        threadA.join();
        threadB.join();
    }

}

operation result

Observed data race,former is62,latter is64
Observed data race,former is8379,latter is8381
Observed data race,former is45385,latter is45387

But if coupled with 

public class ThreadSafeSample {

    public int shareState;
    public void nonSafeAction(){
        while(shareState<100000){
            synchronized(this){
                int former = shareState++;
                int latter = shareState;
                if(former !=latter - 1){
                    System.out.println("Observed data race,former is"+former+","+"latter is"+latter);
                }
            }
        }
    }
    public static void main(String[] args) throws InterruptedException{
        final ThreadSafeSample sample = new ThreadSafeSample();
        Thread threadA = new Thread(){
            public void run(){
                sample.nonSafeAction();
            }
        };
        
        Thread threadB = new Thread(){
            public void run(){
                sample.nonSafeAction();
            }
        };
        
        threadA.start();
        threadB.start();
        threadA.join();
        threadB.join();
    }

}

There will display the results, thus ensuring the safety of

First wrote here today

Guess you like

Origin www.cnblogs.com/pb13/p/11356097.html