preface

To recap:

  • Multiple threads can get through a door in three minutes!
  • Thread source code analysis
  • Multithreading foundation essential knowledge points! Read the learning multithreading twice the result with half the effort

Only skinheads can be strong!

This article is mainly about the Java multi-threaded locking mechanism, there are two kinds:

  • Synchronized
  • Explicit Lock

Have to say a few words:

  • In Java Core Technology Volume 1, the more difficult explicit Lock is introduced first, followed by the simpler Synchronized
  • Java Concurrent Programming In action covers Synchronized piecemeal in its first four chapters, leaving explicit Lock in chapter 13

Synchronized Lock is a Synchronized Lock. Synchronized Lock is a Synchronized Lock. Synchronized Lock is a Synchronized Lock. You don’t have to go through so many chapters.

So let’s get started

A, synchronized lock

1.1 What are synchronized locks?

Synchronized is a Java keyword that locks blocks of code (methods)

  • It is very simple to use, as long as the code block (method) add the keyword synchronized, that is, can achieve synchronization function ~

    public synchronized void test(a) {
        // Follow the public account Java3y
        // doSomething
    }

Copy the code

Synchronized is a mutex

  • Only one thread can enter a locked block at a time

Synchronized is a built-in/monitor lock

  • Every object in Java has a built-in lock (monitor), and synchronized locks blocks of code (methods) using the built-in lock (monitor) on a synchronized object!

1.2 What is synchronized?

  • Synchronized guarantees atomicity of threads. (Protected code blocks are executed once, and no thread accesses them simultaneously.)
  • Synchronized also guarantees visibility. (After synchronized, modified variables are visible to other threads)

Synchronized in Java, through the use of built-in lock, to achieve the synchronization of the variable operation, and then realize the atomicity of the variable operation and the visibility of other threads on the variable, so as to ensure the thread safety in the case of concurrency.

1.3 the principle of synchronized

Let’s start with a snippet of synchronized modifiers and blocks:


public class Main {
	// Modify methods
    public synchronized void test1(a){}public void test2(a){
		// Decorates the code block
        synchronized (this) {}}}Copy the code

Let’s decompile:

Sync code block:

  • Monitorenter and Monitorexit directives

Synchronous methods (not visible here but need to look at the underlying JVM implementation)

  • ACC_SYNCHRONIZED implementation on method modifiers.

Synchronized is underlying through a Monitor object, which has its own object header and stores a lot of information, one of which identifies which thread is holding it.

Please refer to:

  • Blog.csdn.net/chenssy/art…
  • Blog.csdn.net/u012465296/…

1.4 How to use synchronized

Synchronized is generally used to modify three things:

  • General method of modification
  • Modify code block
  • Decorated static methods

1.4.1 Modifying common methods:

The lock used is a Java3y object (built-in lock)


public class Java3y {


    // Modify normal methods with Java3y objects (built-in locks)
    public synchronized void test(a) {
        // Follow the public account Java3y
        // doSomething}}Copy the code

1.4.2 Modify code block:

The lock used is Java3y object (built-in lock)– >this


public class Java3y {
    
    public  void test(a) {
        
        // Decorates a block of code with a Java3y object (built-in lock)-- >this
        synchronized (this) {// Follow the public account Java3y
            // doSomething}}}Copy the code

Of course, we don’t necessarily use this when using synchronized modifier blocks, but we can use other objects (each of which has a built-in lock).

So, here’s what we can do:

public class Java3y {


    // Use object as the lock (any object has a corresponding lock symbol, object is no exception)
    private Object object = new Object();


    public void test(a) {

        // Modify the code block with the lock Object of your own creation
        synchronized (object){
            // Follow the public account Java3y
            // doSomething}}}Copy the code

The above method (using a random object as a lock) is referred to in the book as –> client lock and is not recommended.

The desired feature is to add a putIfAbsent() to the ArrayList, which needs to be thread-safe.

Assume that adding synchronized directly is not feasible

Using client locks, the current implementation is coupled to the original list:

The solution in the book is to use composition (i.e., decorator pattern)

1.4.3 Modify static methods

The class lock (the bytecode file object of the class) is obtained: java3y.class

public class Java3y {

    The static method belongs to the class method. It belongs to the class. The lock obtained is the lock of the class (the bytecode file object of the class)
    public synchronized void test(a) {

        // Follow the public account Java3y
        // doSomething}}Copy the code

1.4.4 Class locks and Object Locks

Synchronized modifies static methods to acquire class locks (bytecode file objects of classes), while synchronized modifies ordinary methods or code blocks to acquire object locks.

  • It is non-conflicting, that is, the thread that acquired the class lock and the thread that acquired the object lock are non-conflicting!

public class SynchoronizedDemo {

    //synchronized modifies non-static methods
    public synchronized void function(a) throws InterruptedException {
        for (int i = 0; i <3; i++) {
            Thread.sleep(1000);
            System.out.println("function running..."); }}//synchronized modifies static methods
    public static synchronized void staticFunction(a)
            throws InterruptedException {
        for (int i = 0; i < 3; i++) {
            Thread.sleep(1000);
            System.out.println("Static function running..."); }}public static void main(String[] args) {
        final SynchoronizedDemo demo = new SynchoronizedDemo();

        // Create a thread to execute static methods
        Thread t1 = new Thread(() -> {
            try {
                staticFunction();
            } catch(InterruptedException e) { e.printStackTrace(); }});// Create thread execution instance methods
        Thread t2 = new Thread(() -> {
            try {
                demo.function();
            } catch(InterruptedException e) { e.printStackTrace(); }});/ / startt1.start(); t2.start(); }}Copy the code

It turns out that class locks and object locks do not conflict!

1.5 reentrant lock

Let’s look at the following code:


public class Widget {

	/ / lock
	public synchronized void doSomething(a) {... }}public class LoggingWidget extends Widget {

	/ / lock
	public synchronized void doSomething(a) {
		System.out.println(toString() + ": calling doSomething");
		super.doSomething(); }}Copy the code
  1. When thread A enters the LoggingWidgetdoSomething()Method,The lock is now held on the LoggingWidget instance object.
  2. The parent Widget’s method is then calleddoSomething()Method, whichSynchronized again.
  3. Now the lock on the LoggingWidget instance object has not been releaseddoSomething()methodsDo you need another lock?

No need!

Because the owner of the lock is “thread”, not “call”. Thread A already has the lock on the LoggingWidget instance object and can continue to “unlock” it when needed.

This is the reentrancy of built-in locks.

1.6 Lock Release Time

  1. The lock is automatically released when the method (block of code) completes execution, and no action is required.
  2. When code executed by a thread is abnormal, the lock it holds is automatically released.
  • There are no deadlocks due to exceptions

Lock An explicit Lock

2.1Lock This section describes the explicit Lock

Lock explicit locking was introduced after JDK1.5, where Synchronized locks were used to keep threads safe

Lock An explicit Lock is an interface, let’s see:

Feel free to translate his top comment to see what it does:

A quick summary:

  • Lock mode to obtain the Lock support interrupt, timeout do not obtain, non-blocking
  • Improved semantics, where to lock, where to unlock have to write
  • Lock Explicit locking gives us great flexibility, but at the same time we have to release the Lock manually
  • Condition objects are supported
  • Allows multiple reader threads to access a shared resource simultaneously

2.2 Synchronized or Lock Which Lock is used

As mentioned earlier, Lock explicit locks give our programs a lot of flexibility, and many features that Synchronized locks don’t have. Is there a need for Synchronized locks?

There has to be!! Lock locks were better than Synchronized locks in many aspects when they first came out, but since JDK1.6 Synchronized locks have undergone various optimizations.

  • Optimized operation: adaptive spin lock, lock elimination, lock coarser, lightweight lock, biased lock.
  • Details may refer to: blog.csdn.net/chenssy/art…

So Lock and Synchronized locks aren’t that different now! Synchronized locks are incredibly simple to use. Lock The Lock must be released manually regardless of its features (this is a danger if you forget to release it)

Synchronized locks are used most of the time, but only with the flexibility that Lock provides

2.3 fair lock

Fair locking is very simple to understand:

  • Threads acquire locks in the order in which they are requested

An unfair lock is:

  • Threads can ** jump the queue ** to obtain the lock while making a request

Lock and Synchronize both use unfair locks by default. Don’t use fair locks unless you have to

  • Fair locking will bring some performance cost

Four, the last

Synchronized built-in locks and explicit locks

  • Synchronized is easy to use, simple, performance is not poor
  • Do not use Lock locks without using the Lock explicit Lock feature.

This is just some introduction, tomorrow will explain its related subclasses and need to pay attention to, please look for ~

Before learning the operating system according to the “Computer operating system – Tang Xiaodan” this book also made a little note, are relatively simple knowledge points. It might be helpful

  • Operating system 1 [Introduction]
  • Operating System Part 2 [Process Management]
  • Operating System Part 3 threads
  • Operating system chapter 4 [Processor scheduling]
  • Operating System Chapter 5 [Deadlock]
  • Operating System Chapter 6 [Memory Management]
  • Operating System Part 7 Device Management

References:

  • Java Core Technology Volume 1
  • Java Concurrent Programming
  • Computer Operating System – Dennis Tang
  • Blog.csdn.net/panweiwei19…
  • www.cnblogs.com/dolphin0520…
  • Blog.csdn.net/chenssy/art…
  • Blog.csdn.net/u012465296/…
  • www.cnblogs.com/wxd0108/p/5…

Open source project (6 K STAR) :Github.com/ZhongFuChen…

If you want to follow my updated articles and shared dry goods in real time, you can search Java3y on wechat.

The content of the PDF document is typed by hand. If you don’t understand anything, you can ask me directly (the official account has my contact information).