Java concurrency Programming--Introduction to thread safety and resolution mechanisms

Source: Internet
Author: User

Brief introduction:

This article mainly introduces the problems that may occur in the Java Multithreaded Environment (thread insecurity) and the corresponding resolution measures. Through this article, you will learn the following pieces of knowledge:

1. Why multi-Threading is required (the advantage of multithreading)

1. Problems with multithreading-thread safety

2. Causes of Thread insecurity

3. What are the ways to resolve thread insecurity

------------------------------------------------------------

Fasten your seatbelt and enter the text below:

A: Why do I need multi-threading?

Threads are an integral part of the Java language, making complex asynchronous code simple, simplifying the development of complex systems, and leveraging the power of computing for multiprocessor systems. Multi-threaded and multi-process differences and choices can refer to my other blog.

(1) Advantages

1. Make full use of hardware resources. Because threads are the basic unit of dispatch for CPUs, if they are single-threaded, they can run at most one processor at a time, meaning that other CPU resources will be wasted. Multithreading can run on multiple processors at the same time, so many threads will be able to take full advantage of the processor's resources as long as the communication between the threads is properly designed.

2. Elegant structure. Multi-thread program can be a huge amount of code, complex programs into a simple function module, each block to achieve a part of the complex program of a single function, which will make the program modeling, testing more convenient, more clear structure, more elegant.

3. Simplify asynchronous processing. To avoid blocking, single-threaded applications must use non-blocking I/O, which is far more complex than synchronous I/O and error prone.

(2) Disadvantages

1. Thread safety: Because multiple threads under the unified process share the same address space and data, and because of the unpredictable nature of the thread execution order, one thread may modify the variables that other threads are using, which facilitates data sharing and, on the other hand, causes dirty reads, Phantom reads, and so on, if handled improperly , fortunately, Java provides a series of synchronization mechanisms to help solve this problem, such as built-in locks.

2. The issue of activity. A long wait lock may occur, even a deadlock.

3. Performance issues. Frequent scheduled switching of threads wastes resources, and the synchronization mechanism causes data in the memory buffers to become invalid and to increase synchronization traffic.

Two: Thread safety

(1) Definition: When multiple threads access a class, regardless of how the runtime environment is scheduled or how those threads will run alternately, and if no additional synchronization or synergy is required in the main debugging code, this class can behave correctly, and is called a thread-safe class. The necessary synchronization mechanisms are encapsulated in the thread-safe classes, so the client does not need to take further synchronization measures.

(2) The cause of thread safety: correctness depends on the alternating execution timing of multiple threads, resulting in a race condition.

(3) Atomic class: You should use atomic classes whenever possible, which makes it easier to analyze thread safety, but it is important to note that classes built with thread-safe classes do not guarantee thread safety. For example, a Atomicinteger get () and Atomicinteger set () are thread-safe, using both methods in a method F () of a class, where f () is thread insecure, because you cannot guarantee that the GET and Set is updated at the same time.

Three: the solution mechanism

1. Add lock.

(1) The lock enables its protected code to be accessed in a serial form, and when a composite operation is locked, it can be manipulated as an atomic operation. The wrong idea is that as long as the method of writing data lock, in fact, this is wrong, all the methods of operation of the data need to be locked, whether it is read or write.

(2) Locking need to consider performance issues, not always blindly to the whole method of locking synchronized on the matter, the method should not affect the shared state and the execution time is longer code separation.

(3) The meaning of locking is not limited to mutual exclusion, but also includes visibility. To ensure that all threads are able to see the latest values, both the read and write operations must use the same lock object.

2. Not sharing status

(1) Stateless objects: Stateless objects must be thread-safe because they do not affect other threads.

(2) thread shutdown: Used only in single-threaded environments.

3. Immutable objects

You can use the final decorated object to ensure thread safety, because the final decorated reference variable (except string) is immutable because the reference is immutable, but the object it points to is mutable, so this class must be published securely, or the interface that modifies the final object cannot be provided externally.

Java concurrency Programming--Introduction to thread safety and resolution mechanisms

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.