I am kite, the public account “ancient time kite”, a not only technology public account, I have been in the app community for many years, mainly Java, Python, React also play 6 slash developer. The Spring Cloud series is complete, and you can check out the full series on my Github. You can also reply “PDF” in the public account to get the full PDF version of my elaborate tutorial.

Class locking and instance locking are common interview questions, from time to time will see students discuss, on the class locking and new out of the class instance locking on the difference?

Today, let you understand the difference between class locking and object locking and how to use it. Keep up, class.

A lock is a lock

Absolute freedom does not exist in life. Absolute freedom usually corresponds to disorder and chaos. Only relative freedom under the constraints of morality, law and ethics can make people feel freedom.

In multithreaded programming, lock is crucial, lock is moral, is legal constraints, no lock multithreaded environment will be chaotic, all threads are fighting for resources, the final result is to cause the system crash, and with the lock, multithreaded environment can work stably and efficiently.

The synchronized keyword

Synchronized is what we call a heavyweight lock, and that heavyweight is relative to the spin locks (AQS), such as a ReentrantLock. A lot of people talk about synchronized, saying it’s bad and too heavy, and it’s plausible. This was true years ago, but Java 1.7 and 1.8 have greatly optimized synchronized to match those lightweight locks.

So, we can safely use it in the program, even if it has not been used, it must be seen in some source code, such as Netty there are many places to use it.

Let’s move on to today’s topic, class locking and instance locking. A class lock is a lock on a class, and an instance is a lock on a class instance.

Instance lock

Once the class is declared, we can create a lot of new instance objects. In this case, each instance in the JVM has its own reference address and heap memory space, and these instances are considered to be independent of each other. Obviously, a lock placed on an instance does not affect the other instances.

There are three common ways to use instance locks:

1. Lock non-static variables in entities

Non-static variables are instance variables and are not shared with other instances, so locking non-static variables declared within entities can achieve object locking. Method blocks that lock the same variable share the same lock.


2. Lock this object

This refers to the current object instance itself, so all synchronized(this) methods share the same lock.


3, direct lock non-static methods

The simplest and most intuitive way is to append the method return type directly.


In the case of object locking, only threads using the same instance are affected by the lock, and multiple instances calling the same method are not affected.

To test this, start five threads, each with a new instance that calls each of the above three methods. The action of the method is to print the thread name and then sleep for 10 seconds.

public class ObjectLock {



private Object lock = new Object();



/ * *

* Lock non-static variables

* @throws InterruptedException

* /


public void lockObjectField(a) throws InterruptedException{

synchronized (lock){

System.out.println(Thread.currentThread().getName());

Thread.sleep(10*1000);

}

}



/ * *

This is the current object instance

* @throws InterruptedException

* /


public void lockThis(a) throws InterruptedException{

synchronized (this) {

System.out.println(Thread.currentThread().getName());

Thread.sleep(10*1000);

}

}



/ * *

* Lock non-static methods directly

* @throws InterruptedException

* /


public synchronized void methodLock(a) throws InterruptedException{

System.out.println(Thread.currentThread().getName());

Thread.sleep(10*1000);

}



public static void main(String[] args){

for (int i = 0; i < 5; i++) {

Thread worker = new Thread(new ObjectLockWorker());

worker.setName("kite-" + i);

worker.start();

}

}



public static class ObjectLockWorker implements Runnable{

@Override

public void run(a) {

try {

ObjectLock objectLock = new ObjectLock();

1 / / way

objectLock.lockObjectField();

2 / / way

//objectLock.lockThis();

3 / / way

//objectLock.methodLock();

} catch (Exception e) {

e.printStackTrace();

}

}

}

}

Copy the code
Our prediction is that each thread will immediately output the thread name and then sleep for 10 seconds.

Call methods 1, 2, and 3 respectively, the effect is the same, we see the output is the same as we predicted, all five threads immediately output the thread name, then wait 10 seconds, the whole program exits.

Kind of lock

Class locks are shared by all threads because class information is stored in the JVM method area, which is shared by all threads.

Class locks can be used in the following ways:

1. Lock static variables in a class

Because static variables, like class information, are in the method section and only have one copy of the entire JVM, adding static variables can achieve the purpose of class locking.


2. Add synchronized directly to static methods

Because static methods also have a method section and only one copy of the entire JVM, adding static methods to a class can achieve the purpose of class locking.

3, lock xxx.class

Class locking is achieved by locking the.class attribute of the current class.


A class lock is a lock shared by all threads, so only one thread can use the locked method or method body at a time, regardless of whether it is the same instance.

In addition to the static method, each thread is called with a new instance. The action completed in the method is to output the thread name, and then sleep for 10 seconds.

public class ClassLock {



private static Object lock = new Object();



/ * *

* Lock static variables

* @throws InterruptedException

* /


public void lockStaticObjectField(a) throws InterruptedException{

synchronized (lock){

System.out.println(Thread.currentThread().getName());

Thread.sleep(10*1000);

}

}



/ * *

* Lock static methods

* @throws InterruptedException

* /


public static synchronized void methodLock(a) throws InterruptedException{

System.out.println(Thread.currentThread().getName());

Thread.sleep(10*1000);

}



/ * *

* locks in XXX in the class

* @throws InterruptedException

* /


public void lockClass(a) throws InterruptedException{

synchronized (ClassLock.class){

System.out.println(Thread.currentThread().getName());

Thread.sleep(10*1000);

}

}



public static void main(String[] args){

for (int i = 0; i < 5; i++) {

Thread worker = new Thread(new ClassLockWorker());

worker.setName("kite-" + i);

worker.start();

}

}



public static class ClassLockWorker implements Runnable{

@Override

public void run(a) {

try {

ClassLock classLock = new ClassLock();

1 / / way

classLock.lockStaticObjectField();

2 / / way

//ClassLock.methodLock();

3 / / way

//classLock.lockClass();

} catch (Exception e) {

e.printStackTrace();

}

}

}

}

Copy the code
We predict that only one thread will grab the lock, output the thread name, wait 10 seconds, then the next thread to grab the lock, output the thread name, and wait 10 seconds. Until the last thread grabs the lock, the whole process takes about 50 seconds.

Call methods 1, 2 and 3 respectively and observe the execution result, which is consistent with our prediction.

conclusion

  1. In the case of object locking, only threads using the same instance are affected by the lock, and multiple instances calling the same method are not affected.

  2. A class lock is a lock shared by all threads, so only one thread can use the locked method or method body at a time, regardless of whether it is the same instance.

Creation is not easy, small praise, big warm, warm me quickly. You’re welcome. Like me!

I am kite, public id “ancient Time kite”, I have been working in the application circles for many years, mainly Java, Python, React also play very 6 slash developer. Can add my friends in the public account, into the group of small partners exchange learning, a lot of dachang students are also in the group yo.