Java Concurrent Programming Practice reading notes-the first part of the basic knowledge

Source: Internet
Author: User
Tags closure visibility volatile

Currently there is no uniform definition of thread safety, and the author summarizes a definition as follows:
This class is thread-safe when multiple threads access a class, regardless of how the runtime environment is scheduled or how those threads will be executed alternately, and if no additional synchronization or coordination is required in the keynote code, and the class is able to behave correctly.

In concurrent programming, a situation in which an indeterminate result occurs due to improper execution of the timing is called a race condition (Race Condition). The most common race condition is the "check after execution (check-then-act)" operation, which determines the next action through an observation that may have failed. A relatively simple example is that two threads to the same 0 of the int variable n (the greater the n the more clearly see the impact of the race condition) times plus one operation, the final result is probably not 2n. Select a point to illustrate this situation, assuming that the target variable x, thread 1 reads x 12, plus one gets 13, this time, thread 2 also read X is 12, the addition of an operation to get 13, then thread 1 writes 13 to X, thread 2 also writes 13 back to X, so that X is 14, and the result X is 13. The code is relatively simple is not posted here, interested friends can try. To avoid this problem, you need to perform an atomic execution of the first check-out operation. The simple way to do this is to use the Synchronized keyword to synchronize the method or code block, which is explained in the next section.

Java provides a built-in locking mechanism to support atomicity: synchronous blocks of code (Synchronized block). The mechanism consists of two parts: an object reference as a lock, and a block of code that is protected by this lock.
Usage One:
Synchronized (lock) {
code block
}

Usage Two:
Public synchronized void SomeMethod () {
Code
}
In the above usage, the two methods of synchronous code block and synchronous method are shown respectively to let the code execute in atomic way. Locking allows the code in the lock protection to be executed atomically because the lock can only be held by one thread, and when a thread holds the lock, the other thread can only wait for the thread holding the lock to release the lock before attempting to acquire the lock. So when a thread enters the synchronization code block to obtain the lock, other threads do not execute this code at the same time, which does not invalidate the data that is read by the thread that enters the code block. There are two points to note
First, usage two does not specify what locks are used, because the synchronization method defaults to this object as a lock.
Second, each shared variable variable should be protected by only one lock.
A better locking convention:
All mutable states are encapsulated inside the object, and all access to the mutable state's code path is synchronized through the object's built-in lock, so that no concurrent access occurs on that object.

Visibility is a complex property, because errors in visibility always violate our intuition.
When it comes to visibility, it's about memory, the variables are stored in memory, and when the thread executes to a method, it reads the required variables into its own workspace, in which case the worker thread is not necessarily aware if the values in memory change. This means that the worker thread does not necessarily see changes in the in-memory variables. This is the problem of visibility. The solution to the visibility problem is the same as the way to solve the race condition: lock. Locking guarantees that only one thread at a time can handle the variable, and the value in the current thread's workspace is always the most recent valid value, and the latest value is written back to memory after the thread has finished processing, and then the other threads are processed again. In this way, for all threads, the variables in memory are visible (all variables in the thread are valid).

Volatile variables are a slightly weaker synchronization mechanism provided by the Java language to ensure that update operations on variables are notified to other threads. In other words, each time a variable of volatile type is accessed, the latest value of the variable is read from memory. The book gives a typical usage

Counting Sheep Program
Volatile Boolean asleep;
...
while (!asleep)
Countsomesheep ();

The program keeps counting sheep when it's not asleep and jumps out of circulation after falling asleep. Because the update to asleep is done in other threads, there is no way for ordinary variables to get the asleep value in time, so it is very appropriate to use the volatile variable.
Note that the volatile variable can only guarantee visibility, that is, the variable will always be consistent with the memory variables, but there is no way to ensure atomicity, so if the volatile variable is based on the previous value of the operation, such as +1 operation, there will be a race condition. The locking mechanism ensures that both visibility and atomicity are ensured.

Thread closure is a technique that does not require the use of synchronization to ensure data security. Race conditions occur because the data is shared across multiple threads. If the required objects are enclosed inside the thread, the race condition will not occur even if the object is not threaded. When you are using thread-blocking techniques, it is usually because you want to implement a particular subsystem as a single-threaded subsystem. Thread closure needs to be planned at design time, it is easier to understand, do not repeat.

Java Concurrent Programming Practice reading notes-the first part of the basic knowledge

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.