Discussion on concurrent programming-thread safety

Source: Internet
Author: User
Tags mutex

In Java concurrent programming, it is very important for thread safety and a problem that must be considered. It can be said that, as long as the network is involved, you must consider thread safety issues. Well, before I start knocking on the code, I think it's necessary to understand some of genteel's theoretical knowledge, because these theories are the basis of thread safety for the code we're knocking out.

When multiple threads access a state variable and one of the threads performs a write operation, the synchronization mechanism must be considered to coordinate access to the variable, and the main synchronization mechanism in Java is the keyword synchronized, which provides an exclusive locking method But the term "synchronization" also includes types of variables, explicit locks (Explicit), and atomic variables.

An error occurs when multiple threads access the same mutable state variable and do not use the appropriate synchronization. There are three ways to fix this 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 state variables

When designing thread-safe classes, good object-oriented technology, non-modifiable, and clear invariance specifications can help.

This class is thread-safe when multiple threads access a class, regardless of how the runtime environment is invoked, or how those threads will be executed alternately, and if the task does not require additional synchronization or co-operation in the keynote code, and the class can behave correctly.

The correctness here is that the behavior of a class is consistent with its canonical security, which means that the class is what functions are implemented correctly.

In a thread-safe class, the necessary synchronization mechanisms are encapsulated, so the client does not need to take further synchronization measures.

The stateless object is mentioned earlier, and the stateless object does not contain any fields or references to the fields in any other class, and it must be thread-safe. Most servlets are stateless, which greatly reduces the complexity of implementing servlet thread security, and the thread becomes a secure thread only if the servlet needs to hold some information while processing the request.

Atomic Nature

A race condition occurs when the correctness of a calculation depends on the alternating execution timing of multiple threads. The so-called race condition is that multiple threads are executed in different order, so the result of execution will vary, and it must be a proper execution order to get the correct result.

Sometimes, in order to ensure atomicity, one measure is to defer initialization, postpone the initialization of the object until it is actually used, and ensure that it is initialized only once.

The Java.util.concurren.atomic package contains some atomic variable classes that are used to implement the atomic state transitions that lie in numeric and object references.

In practice, you should use existing thread-safe objects (such as Acomiclong) to manage the state of the class as much as possible, compared to non-thread-safe objects. It is easier to determine the possible state of a thread-safe object and its state transitions, making it easier to maintain and validate thread security.

Locking mechanism

To maintain state consistency, you need to update the related state variables in a single atomic operation. So what if there are multiple atomic operations that make up an atomic operation? The lock mechanism is used.

1. Built-in lock

Synchronizing code blocks: includes two sections, one object reference as a lock, and one block of code that is most protected by this lock.

synchronized (lock) {     // Access or modify shared status protected by lock }    

Each Java object can be used to implement a synchronous lock. These locks are called built-in locks (intrinsic lock) or monitor locks

The thread automatically obtains the lock before it enters the synchronization code block, and automatically releases the lock when it exits the synchronization code block, regardless of whether it listens to the control path exit, or exits by executing an exception in the synchronous code block. The only way to get a built-in lock is to enter this lock-protected synchronous code block or method.

A Java built-in lock is equivalent to a mutex (or mutex), which means that at most one thread can hold this lock.

Since only one thread can execute a block of built-in locks at a time, a synchronous block of code that is protected by this lock is executed atomically, and multiple lines do not interfere with each other as the code block executes, and the atomicity in the concurrency environment has the same meaning as a transactional application, and a set of statements is executed as an indivisible unit. Any thread that executes a synchronous block of code cannot see that another thread is executing a synchronous block of code that is protected by the same lock.

2. Re-entry

The granularity of the "re-enter" operation to get the lock is "thread", not "call".

Re-entry is an implementation method for each lock associated with a Get count value and an owner thread, when the count value is 0 o'clock, the lock is considered not to be held by any thread. When a thread requests a lock that is not held, the JVM will note the lock's holder, and the Get count value is set to 1. If the same thread acquires the lock again, the count value is incremented, and when the thread exits the synchronization block, the counter decrements accordingly, and the count is 0 o'clock, and the lock is freed.

The re-entry further enhances the encapsulation of the locking behavior, thus simplifying the development of the concurrency-oriented code

To protect the state with a lock

For mutable state variables that may be accessed concurrently by multiple threads, it is necessary to hold the same lock when accessing it, in which case we call the state variable protected by this lock.

There is no intrinsic association between an object's built-in lock and its state, and each object has a built-in lock, just to avoid explicitly creating an object.

A common locking convention is to encapsulate all mutable states inside an object and synchronize all access to the mutable state's code path through the object's built-in lock, so that concurrent access does not occur on the object.

Don't worry. All data requires lock protection, and only variable data that is accessed synchronously by multiple threads needs to be protected.

For each invariant condition that contains multiple variables, all of the variables involved need to be protected by the same lock.

Activity and performance

To ensure that the synchronization blocks are not too small, and do not split the operation that should be atomic into multiple synchronization blocks, you should try to detach from the synchronization code block any operations that do not affect shared state and take longer, so that other threads can access the shared state during the execution of these operations.

You must not have only locks when execution takes a long time to calculate or operations that may not be done quickly (such as network I/O or console I/Os).

Discussion on concurrent programming-thread safety

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.