How to publish and avoid object escape problems in Java?
Publish Object
Simply put, it is to provide a reference to an object to code outside the scope. For example, return an object, or pass it as a parameter to a method of other classes.
Unsafe publishing object example:
<code>@Slf4j</code><code>@NotThreadSafe</code><code>public class UnsafePublish {</code><code><br></code><code> private String[] states = {"a", "b", "c"};</code><code><br></code><code> public String[] getStates() {</code><code> return states;</code><code> }</code><code><br></code><code> public static void main(String[] args) {</code><code> UnsafePublish unsafePublish = new UnsafePublish();</code><code> log.info("{}", Arrays.toString(unsafePublish.getStates()));</code><code> // 发布对象不安全,可被修改</code><code> unsafePublish.getStates()[0] = "d";</code><code> log.info("{}", Arrays.toString(unsafePublish.getStates()));</code><code> }</code><code>}</code>
Object escape
If a class has provided an object reference to the external code and released the object before the construction is completed, it is called an object escape. The escape of the object will Violates thread safety.
<code>public class Escape {</code><code> private int thisCanBeEscape = 1;</code><code><br></code><code> public Escape() {</code><code> new InnerClass();</code><code> // 还有业务需要执行</code><code> thisCanBeEscape++;</code><code> }</code><code><br></code><code> private class InnerClass {</code><code> public InnerClass() {</code><code> log.info("{}", Escape.this.thisCanBeEscape);</code><code> }</code><code> }</code><code><br></code><code> public static void main(String[] args) {</code><code> new Escape();</code><code> }</code><code>}</code>
The instance of this inner class contains a reference to the private domain object of the encapsulated instance. It will be released before the object is correctly constructed, which may be unsafe. Inside, there is an error that causes this reference to overflow during construction.
The above code starts a thread during function construction. Whether it is implicit startup or explicit startup, it will cause the overflow of this reference. The new thread will always see the owning object before it is constructed.
Explanation of class name.this
The syntax of "class name.this" is called "qualified this" in the Java language. The main purpose of this syntax is: in the method of an inner class, when you want to specify the "this" reference of an outer class at a certain nested level, use the "outer class name.this" syntax. For example:
class Foo { class Bar { Foo getFoo() { return Foo.this; } }}
In the getFoo() method in the Foo.Bar class, if you write "this" directly, it refers to the instance of the Foo.Bar class, and if you want to specify the this instance of the peripheral Foo class , it must be written as Foo.this here. In particular, if you write Bar.this in the getFoo() method in the above example, the effect is the same as writing this directly, specifying the current Foo.Bar class instance.
Safely publish objects
Initialize an object reference in the static initialization function
Save the object reference to the volatile type field or AtomicReference object
Save the reference of the object to a final type field of a correctly constructed object
Save the reference of the object To a domain protected by a lock
You can think of the hungry mode/lazy mode in the singleton mode.
Safe shared object policy
Thread restriction: An object restricted by a thread is exclusive to the thread and can only be modified by the thread that owns it.
Shared read-only: A shared read-only object can be accessed concurrently by multiple threads without additional synchronization, but no thread can modify it.
Thread-safe object: A thread-safe object or container uses a synchronization mechanism to ensure thread safety internally, so other threads can access it at will through the public interface without additional synchronization.
Guarded object: The guarded object can only be accessed by acquiring a specific lock.
The above is the detailed content of How to publish and avoid object escape problems 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

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.
