Home Java javaTutorial How to use synchronized to implement synchronization mechanism in Java?

How to use synchronized to implement synchronization mechanism in Java?

Apr 22, 2023 pm 02:46 PM
java synchronized

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(){   //….   }
Copy after login

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)   {          //…..   }   }
Copy after login

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)   {          //…..   }   }
Copy after login

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) { //… }   }   //…..   }
Copy after login

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(类名称字面常量)   }          }
Copy after login


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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

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

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

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

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

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.

How to Run Your First Spring Boot Application in Spring Tool Suite? How to Run Your First Spring Boot Application in Spring Tool Suite? Feb 07, 2025 pm 12:11 PM

Spring Boot simplifies the creation of robust, scalable, and production-ready Java applications, revolutionizing Java development. Its "convention over configuration" approach, inherent to the Spring ecosystem, minimizes manual setup, allo

See all articles