Java Efficient concurrency

Source: Internet
Author: User
Tags thread class visibility volatile

A period of time did not review multithreading related knowledge, although the work will use a number of multi-threaded content, but are biased to the foundation, today reread multi-threaded related content, found that some things still need attention. These are usually interview high-frequency problems.

Understanding concurrency Insider is an indispensable course for a senior programmer

Java memory model

Note that the Java memory Model (JMM) and the JVM runtime data area are not the same concept, and another concept is that the Java object model can be taken out separately next time.

    • JMM are all around the atom, the visibility, the order of the
    • JMM defines how the JVM interacts with the computer's memory

All thread-to-variable operations need to be done in working memory and cannot be manipulated directly into the main memory.

Interactive operations between Memory:
Lock,unlock Main Memory
Read,write Main Memory
Load,store Variables for working memory
Use,assign Variables for working memory

More information on JMM view, multi-thread Java memory model

Volatile

Volatile can be said to be the most lightweight synchronization mechanism available within a Java virtual machine, which guarantees only visibility and ordering, and does not guarantee atomicity.

Visibility: When a thread modifies the value of this variable, the new value is immediately known to other threads, and two other keywords that can achieve visibility: Synchronized andfinal

Order: If you look inside this thread, all operations are ordered, and if another thread is observed in one thread, then all operations are unordered.

Java and threading

Concurrency does not necessarily depend on multi-threading, such as multi-process concurrency common in PHP. All the key methods of the Java thread class are declared as native, so Java does not implement threads on its own.

Three ways to implement threads: using kernel threading implementations, using user thread implementations, and using user-line loads for more lightweight processes.

    1. Kernel thread implementation (Klt,kernel-level thread). Programs generally do not use kernel threads directly, but instead use an advanced interface of kernel threads, lightweight processes (Lwp,light Weight process,lwp) with kernel threads before they can be lightweight.

Cons: Various threading operations, such as creation, destruction, and synchronization require system calls, and system calls are expensive and need to be switched back and forth between the user state and the kernel state. Consuming kernel resources, a system that supports a lightweight number of processes is limited.

    1. User thread implementation, broadly speaking, a thread can be a user thread as long as it is not a kernel thread. User threads complete in the user state, without the help of the kernel, can support a larger number of threads.

Cons: Without kernel support, various operations are more complex. Now it's basically deprecated.

    1. User threads + lightweight processes, combining a bit of both, the user process and the number of lightweight processes is variable.
Thread scheduling

Cooperative scheduling: The advantage is that the implementation is simple, the switch operation on the thread itself is known, no thread synchronization problem, the thread to do their own things after the thread switch.

Cons: If program writing is not stable, then the system is not controllable. A process that insists on not letting the CPU execute implementation will cause the system to crash.

Preemptive scheduling (Java default scheduling): Each thread is assigned the execution chord by the system, and the thread switch is not determined by the thread, and the system can kill the process when a problem occurs.

Note: The higher the priority of the thread, the higher the thread will be, but the more likely it is that the higher priority thread is chosen.

Java Thread State transitions

Put a picture on it and remember it well:

How to implement thread safety
    • Mutex synchronization, lock-in, pessimistic scheme, guaranteed to share data only one thread access at a time. , mutual exclusion is the result of synchronization is the fruit.
    • Non-blocking synchronization, CAS, optimistic scenario, first operation, if no other threads are also operating, then the operation succeeds, if other threads are also operating the shared data, then try again.
    • No synchronization scenario, typically pure code, with some features, such as not relying on the public system resources on the heap
Lock optimization
    • Spin lock and self-adapting spin
      If the shared data will only last for a very short period of time, it is not worthwhile to suspend and resume the thread for this time, we can let the thread that requests the lock wait a moment, let the thread do a busy loop (spin), this is called the spin lock.

Because sometimes it is not worth sharing data in the end is locked for how long, blind spin can lead to loss of performance, after JDK1.6, the system introduced adaptive spin, and when the shared data is locked, the system can allow the thread spin more time longer. If the spin lock is not obtained many times, the next time the system may omit the spin lock.

    • Lock removal
      Eliminate some locks that are not likely to compete for shared data.

    • Lock coarsening
      Sometimes multiple operations lock the same object, and frequent locking can also affect performance, so the system expands the synchronization range of the lock. Multiple append operations, such as StringBuffer ().

    • Biased lock
      It can be understood that the lock is biased toward the first thread to get it, and if the lock is not fetched by another thread during the next execution, the thread holding the biased lock will never be synchronized.
At last

Understanding concurrency Insider is an indispensable course for a senior programmer

Reference
    • In-depth understanding of the JVM

Java Efficient concurrency

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.