Java Concurrency Programming (ix) security release

Source: Internet
Author: User

The previous discussion was on how to block objects in the thread, which would reduce the synchronization and visibility issues associated with concurrency. But at some point, we want to share objects across multiple threads, and we must ensure that they are shared securely.

"Examples of unsafe publications"

visibility issues; Other threads see an inconsistent state; The object has not yet been created and is published.

Incorrect publication: The correct object is destroyed

The object that was completely created is not yet complete, and publishing it will cause the other threads to see an inconsistent state, and then see the state of the object suddenly changing, even if the thread hasn't modified it since the object was published.

"Sample Code"

There are two possible scenarios in which an object is not published correctly:

1. The domain of objects seen by other threads may be a null reference, or a previous old value;

2. Worse, a thread sees a reference to an object that is up-to-date, but the value of the object's state is invalid;

3. The default value that the thread gets when it reads the domain for the first time, and it gets an updated value when it is read again.

Immutable objects and initialization security

Because immutable objects are a very important object, the Java memory model provides a special type of initialization security guarantee for the sharing of immutable objects. (What guarantee)

To ensure that the object state renders a consistent view, you must use synchronization.

On the other hand, even when you publish a reference to an immutable object without using synchronization, you can still access the object safely.

To maintain this security of initialization, all requirements for immutability must be met: The state cannot be modified, all fields have a final type, and the correct construction process.

The constructor of object writes the default values to all fields before the subclass constructor is run, so the default value for a domain may be treated as a failure value.

Any thread can safely access immutable objects without requiring additional synchronization, even if they are published without using synchronization.

This guarantee will also extend to the domain where all fianl types in the object are created correctly. In the absence of additional synchronization, it is also possible to securely access domains of the fianl type. However, if a field of type fianl points to a mutable object, the state of the object to which the domain is accessed still needs to be synchronized.

Common patterns for Secure publishing

Mutable objects must be published in a secure manner, which usually means that synchronization must be used when the thread of the object is published and used.

The thread that uses the object can see that the object is in a published state, and later describes how to modify its visibility after the object is published.

To safely publish an object, the reference to the object and the state of the object must be visible to other threads at the same time. A properly constructed object can be safely published in the following ways.

(The relationship between the object's reference and the state of the object has never been considered before, and references are not guaranteed to get the state of the object?) This is not the case)

    • Initializes a reference to an object in the static initialization function.
    • Holds the object's reference to a volatile type of field or Atomicreference object.
    • Saves a reference to an object in the final type field of a properly constructed object.
    • Saves a reference to an object in a lock-protected domain.

Synchronization within a thread-safe container means that the last requirement is met when the object is placed into a container, such as a vector or synchronizedlist. If thread a puts object x into a thread-safe container and then thread B reads the object, you can make sure B sees the X state of the A setting, even if there is no explicit synchronization in the application code for this read/write X.

By speaking a key or value into Hashtable,synchronizedmap or concurrentmap, it is safe to publish it to any thread that accesses it from those containers (whether accessed directly or through an iterator). By placing an element in a vector, copyonwritearraylist, Copyonwritearrayset, synchronizedlist, or Synchronizedset, This element can be safely published to any thread that accesses the element from those containers. By putting an element into Blockingqueue or concurrentlinkedqueue, you can safely publish the element to any thread that accesses the element from those queues.

Other data-passing mechanisms in the class library, such as future and exchanger, also enable secure publishing.

In general, the simplest and safest way to publish a statically constructed object is to use static initialization:

"Code Demo"

Static initialization is performed by the JVM during the initialization phase of the class. Since there is a synchronization mechanism within the JVM, any objects initialized in this manner can be safely published.

Fact Non-mutable object

If an object is not modified after it is published, it is sufficient for other threads that securely access these objects without additional synchronization. If an object is technically mutable, but its state does not change after it is published, the object is called a fact-immutable object (effectively immutable objects).

In the absence of additional synchronization, any thread can safely use the fact immutable object that is released safely.

For example, date itself is mutable, but if it is used as an immutable object, the use of locks can be omitted when a Date object is shared among multiple threads.

mutable objects

For mutable objects, you need to use synchronization not only when you publish an object, but also with synchronization every time you access the object to ensure the visibility of subsequent modifications. To safely share mutable objects, these objects must be securely published and must be thread-safe or protected by a lock.

The publication requirements of an object depend on its variability:

Immutable objects can be published by any mechanism.

Fact-immutable objects must be published in a secure manner.

Mutable objects must be published in a secure manner and must be thread-safe or protected by a lock.

Securely share objects

When you get a reference to an object, you need to know what can be done on that reference. Do I need to get a lock before using it? Is it possible to modify its state, or can it only read it? Many concurrency errors are caused by the lack of understanding of these "established rules" of shared objects. When you publish an object, you must explicitly describe how the object is accessed.

There are several policies that you can use when concurrent programs use and share objects:

Thread closure: A thread-closed object can only have one thread owned, the object is enclosed in that thread, and can only be modified by this thread.

Read-only sharing: In the absence of additional synchronization, a shared read-only object can be accessed concurrently by multiple threads, but cannot be modified by any thread. Shared read-only objects include immutable objects and fact-invariant objects.

Thread-safe sharing: Thread-safe objects are synchronized internally, so multiple threads can be accessed through the public interface of the object without requiring further synchronization.

Protected objects: Protected objects can only be accessed by holding a specific lock, which includes objects encapsulated in other thread-safe objects, and objects that have been published and protected by a particular lock.

Java Concurrency Programming (ix) security release

Related Article

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.