Table of Contents
Publish Object
Object escape
Explanation of class name.this
Safely publish objects
Safe shared object policy
Home Java javaTutorial How to publish and avoid object escape problems in Java?

How to publish and avoid object escape problems in Java?

Apr 22, 2023 pm 02:37 PM
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>
Copy after login

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>
Copy after login
  • 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;    }  }}
Copy after login

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

  1. Initialize an object reference in the static initialization function

  2. Save the object reference to the volatile type field or AtomicReference object

  3. Save the reference of the object to a final type field of a correctly constructed object

  4. 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

  1. Thread restriction: An object restricted by a thread is exclusive to the thread and can only be modified by the thread that owns it.

  2. Shared read-only: A shared read-only object can be accessed concurrently by multiple threads without additional synchronization, but no thread can modify it.

  3. 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.

  4. 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!

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)

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

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

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

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

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

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

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

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

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

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

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.

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. 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.

See all articles