How to use synchronized to implement synchronization mechanism in Java?
Summary of how to use synchronized in Java
1. When using synchronized as a function modifier, the sample code is as follows:
Public synchronized void method(){ //…. }
This is the synchronization method. So which object is synchronized locked at this time? What he locks is calling this synchronized method object. In other words, when an object P1 executes this synchronization method in different threads, they will form mutual exclusion to achieve synchronization effect. However, another object P2 generated by the Class to which this object belongs can arbitrarily call this method with the synchronized keyword added.
The sample code above is equivalent to the following code:
public void method() { synchronized (this) // (1) { //….. } }
What does this at (1) refer to? He refers to the object that calls this method, such as P1. It can be seen that the essence of the synchronization method is to apply synchronized to the object reference. ——Only the thread that has obtained the P1 object lock can call the synchronization method of P1. As far as P2 is concerned, the P1 lock has nothing to do with it. The program may also get rid of the control of the synchronization mechanism in this case, resulting in data confusion.
2. Synchronization block, the sample code is as follows:
public void method(SomeObject so) { synchronized(so) { //….. } }
At this time, the lock is the so object, and whoever gets the lock can run the code he controls. When there is a clear object as the lock, you can write the program like this, but when there is no clear object as the lock and you just want to synchronize a piece of code, you can create a special instance variable (it must be an object) to act as the lock:
class Foo implements Runnable { private byte[] lock = new byte[0]; // 特别的instance变量 Public void method() { synchronized(lock) { //… } } //….. }
Note: A zero-length byte array object will be more economical to create than any object - view the compiled bytecode: generating a zero-length byte[] object requires only 3 opcodes, while Object lock = new Object() requires 7 lines of opcode.
3. Apply synchronized to a static function. The sample code is as follows:
Class Foo { public synchronized static void method1() // 同步的static 函数 { //…. } public void method2() { synchronized(Foo.class) // class literal(类名称字面常量) } }
The method2() method in the code uses class literal as a lock. The effect it produces with the synchronized static function is Similarly, the lock acquired is very special, it is the class (Class, rather than a specific object generated by this Class) to which the object currently calling this method belongs.
I remember that I saw in the book "Effective Java" that using Foo.class and P1.getClass() for synchronization locks is not the same. You cannot use P1.getClass() to achieve the purpose of locking this Class. P1 refers to the object generated by the Foo class.
It can be inferred: If a synchronized static function A is defined in a class, and a synchronized instance function B is also defined, then when the same object Obj of this class accesses the A and B methods respectively in multiple threads, There will be no synchronization because their locks are different. The lock of method A is the Class to which Obj belongs, and the lock of method B is the object to which Obj belongs.
A summary of how to use synchronized in Java is as follows:
Knowing which object synchronized locks can help us design safer multi-threaded programs.
There are some more techniques that can make our synchronous access to shared resources more secure:
1. Define private instance variables and their get methods instead of public/protected instance variables. If the variable is defined as public, the object can directly obtain it and change it from the outside world, bypassing the control of the synchronization method. This is also one of the standard implementation methods of JavaBean.
2. If the instance variable is an object, such as an array or ArrayList, then the above method is still unsafe, because when the external object gets the reference of the instance object through the get method and points it to another object, then the private variable is If it changes, wouldn't it be dangerous? At this time, you need to add synchronized synchronization to the get method, and only return the clone() of this private object - in this way, the calling end gets a reference to the object copy.
The above is the detailed content of How to use synchronized to implement synchronization mechanism in Java?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.
