Java Concurrent Programming-1

Source: Internet
Author: User

Volatile variable

The role of the Volatile keyword:

    • Ensure that actions on declared variables are not reordered with other memory operations
    • Volatile variables are not cached to registers or other places where the processor is hidden (guaranteed visibility)
    • Ensure that the reference type, long and double the atomic value of the Read or assignment

Main uses of Volatile:

    • Ensure the visibility of the state of the objects they reference
    • Ensure long the atomicity of reading or assignment and double type
    • Ensure visibility of flag status changes
Release and Escape

Publish: An object can be used by code outside the current scope. Like what:

    • Passed as a parameter to another method
    • Returns a reference to this object as a return value

Escape: An object is released when it is not ready. Like what:

    • The constructor has a parameter of the collection type, but in the constructor collection.add(this) , this it is escaped.

Note: Do not start a thread in the constructor. Because when an object creates a thread in the constructor, either explicitly or implicitly, the this reference is almost always shared by the new thread. You can create a thread in the constructor, but don't start it!

Thread closure

Threads need to be synchronized because the data is shared between threads . So the way to avoid synchronization is to not share data , also called thread closure .

The JDBC object of the application pool is a thread-gated example, where each Connection object is always exclusive to a thread until it is returned to the pool.

Ad-hoc Thread Limits

Features: Error prone, should be replaced with stack limit and ThreadLocal.

Stack limit

Local variables are restricted to the execution thread, they exist in the execution line stacks , and other threads cannot position the stack.

Note: Make sure that local variables are not escaped!

ThreadLocal

ThreadLocalMultiple objects can be bound in the execution thread, ThreadLocal providing the get and set methods to maintain a separate copy of each thread that uses it.

ThreadLocalCommonly used in:

    1. Prevent incorrect sharing in designs based on mutable monomers or global variables. such as SimpleDateFormatter andConnection
    2. A frequently performed operation requires a temporary object such as buffer and avoids reassigning the temporary object each time.

Threadlocal:every thread has a threadlocals map structure to store value related on the thread.

When calling Threadlocal.get ():

    1. ThreadLocal Firstly try to get the Threadlocals map structure:

      • If the map is null, then create the map and put a (this, initialvalue) to the map, then return the value
      • If the map is not null and then try to get value from the map

        • If the value is null and then insert the InitialValue to the map (this, initialvalue) and then return the value
        • If the value is not NULL, return the value
Immutable objects

The publication object depends on the variability of the object:

    1. Immutable objects can be published by any mechanism
    2. Efficient immutable objects must be published securely
    3. Mutable objects must be securely published and must be thread-safe or lock-protected
Immutable objects:

Immutable objects are objects whose post-construction state cannot be changed. Because of its immutability, he will not have Thread interference and Memory inconsistent so on.

Characteristics of Immutable objects:

    1. Do not set the setter method.
    2. All members are set to final +private
    3. Subclasses are not allowed to override methods. The simple approach is to put the class declaration before the +final
    4. If there are reference types in the instance variables, do not let them be changed:

      • Do not provide a way to change them
      • Do not share their references, including

        • Do not directly reference parameters in constructors
        • Do not return the instance reference variable, if you have to, return the copy!

Immutable objects are always thread-safe. It has only one state and cannot be changed. Immutable objects have the following characteristics:

    1. is created correctly (no this reference escapes during creation)
    2. All fields are final types
    3. The status cannot be modified after it is created

Note: If the final domain points to mutable objects, you still need to synchronize when accessing the state of those objects.

How can I guarantee the visibility of an immutable object ?

    1. Static initializer Initializes a reference to the object
    2. Store its references to a volatile domain orAtomicReference
    3. Store its reference in the domain of the object you created correctly final
    4. Its reference is stored in a domain that is properly protected by the lock
Valid immutable objects

An object is not technically immutable, but its state is not modified after it is published, such an object is called a valid immutable object.

Any thread can safely use a highly efficient and immutable object that is securely released without additional synchronization.

mutable objects

Security releases only guarantee visibility of the "release at the time" state. But then the change of state requires thread synchronization to ensure.

Java Concurrent Programming-1

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.