I. Introduction to thread safety in multithreaded programming

Source: Internet
Author: User

Security

A, writing thread-safe code, the core is to the state of access, change and other operations to manage, especially to the shared, variable state access. The main synchronization mechanisms in Java are synchronized (exclusive locks), volatile types of variables, explicit locks, and atomic variables.

b, how to fix the synchronization problem:

1. Do not share this state variable between threads

2. Modify the state variable to be an immutable variable

3. Use synchronization when accessing or modifying state variables

C, when multiple threads access a class, the class always shows the correct behavior, calling the class thread-safe.

D, stateless objects must be thread-safe.

Atomic nature:

1. Conditions of condition: when the correctness of a calculation depends on the alternating execution timing of multiple threads, the condition of normality occurs. (Perform, read, modify, write operations before checking)

2, composite operation: First check after the execution, read, modify, write the operation

3. When a state is added to a stateless class, the class is still thread-safe if the state is managed by a thread-safe object.

Built-in Lock:

1, each object has a built-in lock, and is mutually exclusive.

2, re-enter the sex: When a thread acquires a lock, the JVM records the bearer of the lock, and the Get count value is set to 1, as if a thread acquires a lock at a time (a synchronous method in the same class synchronizes the B-sync method), the count value is incremented, and the counter is reduced by one when it exits the synchronization code block, and when it is 0 o'clock, This lock will be released.

I. Introduction to thread safety in multithreaded programming

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.