How to safely publish an object

Source: Internet
Author: User

Object publication: Enables an object to be used in code outside the current scope

How can I safely publish an object?

1: mutable objects such as the release by means of locking

2: Immutable objects can be freely released

A mutable object must be published in a secure manner, which means that the thread that publishes and uses the object must use synchronization.

To secure a publishing object, the state of the object and the reference to the object must be visible to other threads, common practices include:

1: Initializing an object reference in a static initialization function

2: Save the object's reference to a volatile type field

3: Save the object's reference to the correct constructed object's final field

4: Save the object's reference to a lock-protected domain

5: Using a thread-safe container

6: The simplest and safest way to use statically constructed objects is to use static initializers.

public static Holder Holer = new Holder (23);

The reason is that the static initializer is performed by the JVM during the initialization phase of the class, and because there is a synchronization mechanism inside the JVM, any objects that can be initialized in this manner can be safely published.

How to safely publish an object

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.