Multithreading (ii) Building thread-safe classes

Source: Internet
Author: User
Tags volatile

  • Building Thread-Safe classes
    • Volatile
      • Only data visibility is guaranteed and data synchronization is not guaranteed. That is, the JVM only guarantees that the most recent values are exposed to all threads after using volatile data changes, and that there is no multiple limit on the operation of the cached data within the thread. Multiple threads changing a shared volatile data at the same time does not produce the correct results.

    • You can use volatile when the following conditions are true:
      • 1. Write a variable without relying on the current value of the variable, or you can ensure that only a single thread modifies the value of the variable.

      • 2. Variables do not need to participate in invariant constraints with other variables.

      • 3. There is no other reason to lock when accessing a variable.

    • Long and double
      • 64-bit data, divided into the upper and lower 32-bit two parts, its operation is not atomic operation.

    • Release
      • An object can be used by code outside the current scope.

      • Do not publish objects and start threads in constructors.

    • Escape
      • An object is released when it is not ready. The class object may have been allocated space (not NULL), but the internal data has not yet completed initialization.

    • Secure Release Mode
      • Initializes an object reference through a static initializer;

      • Storing its references to volatile or atomicreference;

      • Store its references in a properly created final domain, or in a lock-protected domain.

    • Secure shared objects
      • Thread limit: A thread-restricted object that is exclusive to the thread and can only be modified by the thread that owns it (such as threadlocal type data).

      • Shared read-only: A shared read-only object.

      • Shared thread safety: A thread-safe object is internally synchronized so that other threads can be accessed without additional synchronization.

      • Guarded (Guarded): A published object that is protected by a lock.

    • Thread-Safe Composite objects
      • Develop a synchronization policy (how to coordinate access to objects by other threads without violating immutable constraints). ) and document it.

      • Instance limits
        • Objects are encapsulated in another object, such as objects in HashSet, to convert access restrictions on encapsulated objects to the encapsulated data access path for encapsulated objects (HashSet instances).

      • Java Monitor mode (Java internal lock)
        • Implemented by locks.

      • Delegate thread Safety
        • If a class consists of multiple thread-safe state variables that are independent of each other, and the operation of the class does not contain any transitions of invalid states (such as check-then-act), it can be said that thread-safe delegation to these state variables.

      • Extended Thread-Safe classes
        • Replaces the lock emulation of the extended object with the internal lock of the composite object.

  • Avoid risk of activity
    • Dead lock
      • Lock sequence Deadlock (lock-ordering deadlock)
        • Lock order deadlocks Do not occur if all threads acquire locks in a common, fixed order.

        • The method (A, A, b) parameter represents an instance that may be the same instance but in a different order. such as transfer, from me-he and from him-I, the lock order is different.

      • Resource Deadlock (Resource deadlock)
        • Threads waiting for each other and holding each other's required resources

      • Deadlock between collaboration objects
        • Calling an external method while holding a lock is challenging the activity issue. External methods may acquire additional locks (the risk of life-and-death locks) or encounter severe timeout blocking. When you hold a lock, you delay the thread that the other view gets the lock on.

    • Open Call
      • Does not create a lock problem.

    • Avoiding and diagnosing deadlocks
      • Try a timed lock
        • If the lock is acquired in a nested method, you cannot just release the outer lock.

      • Parsing deadlocks by thread dump
        • Unix:kill-3 or Ctrl-\,windows:ctrl-break. The lock shown under JDK version 5 will not dump, and there will be sketchy information under JDK version 6

    • Other active risk (loss of signal, live Lock)
      • Hunger (starvation)
        • Endless waiting for resources.

      • Weak responsiveness
        • Competing with other threads for resources causes poor responsiveness.

      • Live Lock (Livelock)
        • Deadlocks do not occur but are not responsive due to repeated error scenarios, and are avoided by random waits and withdrawals.

  • Performance and Scalability
    • Avoid premature optimizations: first make the program correct, and then speed up.

    • Amdahl Law (Amdahl Law)
      • S=1/(1-a+a/n)

      • A is the proportion of the parallel computing part, N is the number of parallel processing nodes.

      • 1-a=0 (only parallel) the maximum speedup is n;

      • When A=0 (only serial) the minimum acceleration ratio is s=1;

      • When n approaches Infinity, the computational speedup is s->1/(1-a), which is the upper limit of speedup.

    • Cost of thread ingestion
      • Switch context: Competing CPUs and data caching

      • Memory Sync: Storage levels (memory barrier) instructions-flush cache, invalidate cache, flush hardware write buffers, and defer delivery of execution (most operations cannot be reordered in storage levels).

      • Blocking: Blocked threads may spin to wait or hang, spin is more suitable for short waits, and hang for long waits.

      • In most general-purpose processors, the context switching overhead is equivalent to 5k-10k clock cycles, or a few microseconds.

    • Reduction of lock competition (lock requested frequency * Holding time of the lock)
      • Reduce the time to hold the lock.

      • Increase concurrency by reducing the frequency of request locks or coordinating mechanisms to replace exclusive locks.

      • Reduce the range of locks: Remove the lock-independent code from the synchronized block, especially blocking operations, such as I/O operations.

      • Reduce the granularity of the lock: implemented by a split lock (lock splitting), a split lock (lock striping). However, it is more difficult to lock exclusive access to the container, such as when the value of the CONCURRENTHASHMAP needs to be expanded or re-queued.

      • Avoid hotspot domains

      • Overrides for exclusive locks: concurrent containers, read and write locks, immutable objects, atomic variables.

    • Detecting CPU Utilization
      • Not enough load

      • IO limit: You can determine whether a program is restricted to disk by Iostat or perfmon, or whether it is limited by bandwidth through network monitoring.

      • External restrictions: such as databases, WebService, and so on.

      • Lock competition.

      • Object pooling: Consider the performance comparison between the GC pressure caused by frequently created objects and the lock switching of the pool technology.

This article is from the Java Technology Stack notes blog, so be sure to keep this source

Multithreading (ii) Building thread-safe classes

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