Concurrent Programming-thread security and Programming

Source: Internet
Author: User

Concurrent Programming-thread security and Programming

In Java concurrent programming, thread security is very important and must be considered. as long as the network is involved, thread security issues must be considered. well, before I start coding, I think it is necessary to understand some theoretical knowledge, because these theoretical knowledge is a basis for whether the code we have typed is thread security.

When multiple threads access a certain state variable and one of them executes the write operation, you must consider using a synchronization mechanism to coordinate these threads to access the variable, the main synchronization mechanism in Java is the keyword synchronized, which provides an exclusive locking method. However, the term "synchronization" also includes type variables and Explicit locks (Explicit) and atomic variables.

If appropriate synchronization is not used when multiple threads access the same variable in the variable state, an error occurs. There are three ways to fix this problem:

1) The status variable is not shared among threads.

2) change the status variable to an unchangeable variable.

3) Use synchronization when accessing status variables

When designing thread-safe classes, good object-oriented technology, unmodifiable, and clear immutability specifications can be helpful.

When multiple threads access a class, no matter what calling method is used in the runtime environment, or how these threads will be executed alternately, and no extra synchronization or collaboration of tasks is required in the main code, this class can show correct behavior, so it is called thread security.

The correctness here means that the behavior of a class is consistent with its standard security. That is to say, the class correctly implements what functions are implemented.

The thread-safe class encapsulates the necessary synchronization mechanism, so the client does not need to take further synchronization measures.

As mentioned above, stateless objects do not contain any domain or reference of any other domain in the class. Stateless objects must be thread-safe. most servlets are stateless, greatly reducing the complexity of Servlet thread security. Only when the Servlet needs to save some information when processing requests, the thread will become a safe thread.

Atomicity

When a computing is correct depends on the time sequence of multiple threads, a race condition occurs. the so-called race condition is that the execution order of multiple threads is different, so the execution results will be different. It must be a correct execution order to produce the correct results.

Sometimes, to ensure atomicity, a method is used to delay initialization. The initialization operation of the object is postponed until it is used. At the same time, it must be initialized only once.

The java. util. concurren. atomic package contains atomic variable classes used to convert atomic states in numeric values and object references.

In actual situations, we should try our best to use existing thread-safe objects (such as acacacmiclong) to manage the state, compared with non-thread-safe objects. it is easier to determine the possible state of a thread-safe object and its state conversion, which makes it easier to maintain and verify thread security.

 

Locking Mechanism

To maintain state consistency, you need to update related state variables in a single atomic operation. What if multiple atomic operations constitute an atomic operation? The locking mechanism is used.

1. built-in locks

Synchronous Code block: contains two parts: one is the reference of the lock object and the other is the code block of the object most protected by the lock.

Synchronized (lock) {// access or modify the shared status protected by the lock}

Each Java object can be used as a synchronization lock. These locks are referred to as built-in locks (Intrinsic locks) or Monitor locks (Monitor locks)

The thread automatically acquires the lock before it enters the synchronization code block and releases the lock when it exits the synchronization code block. Whether it has heard of the control path exit or throws an exception and exits through execution in the synchronization code block. The only way to obtain the built-in lock is to enter the lock-protected Synchronous Code block or method.

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

Since only one thread can execute a built-in lock code block at a time, the synchronized code block protected by this lock is executed in atomic mode in meetings, and multiple lines will not interfere with each other when executing the code block, the atomicity in the concurrent environment has the same meaning as the transaction application. A group of statements are executed as an inseparable unit. It is impossible for any thread that executes the synchronization code block to see that other threads are executing the synchronization code block protected by the same lock.

2. reimport

The granularity of the "re-import" lock acquisition operation is "Thread", rather than "call ".

Re-entry is implemented by associating a get Count value and an owner thread for each lock. When the Count value is 0, this lock is considered to be held by no thread. When the thread requests an unheld lock, the JVM will write down the holder of the lock and set the Count value to 1. if the same thread obtains the lock again, the Count value increases. When the thread exits the synchronization code block, the counter decreases accordingly. When the Count value is 0, the lock is released.

The re-entry further improves the encapsulation of locking behavior. Therefore, it simplifies concurrent code-oriented development.

 

Use locks to protect status

For variable state variables that may be accessed by multiple threads at the same time, the same lock must be held during access. In this case, we call the state variable protected by this lock.

There is no internal association between the built-in lock of an object and its State. Every object has a built-in lock to avoid explicit object creation.

A common locking convention is to encapsulate all the variable states in the object and synchronize all the code paths that access the variable state through the built-in lock of the object, this prevents concurrent access to this object.

The lock protection is required for all data. Only variable data accessed by multiple threads must be protected.

For immutable conditions that contain multiple variables, all variables involved must be protected by the same lock.

 

Activity and Performance

Make sure that the synchronization code block is not too small, and do not split the operations that should be atomic into multiple synchronization code blocks, try to remove operations that do not affect the sharing status and take a long time from the synchronization code block, so that other threads can access the sharing status during the execution of these operations.

Do not only lock operations that take a long time to complete or may not be completed quickly (such as network I/O or console I/O.

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.