Software constructs concurrent 3 (thread safety)----locking and synchronizing

Source: Internet
Author: User
Tags volatile

Synchronization: Prevents threads from accessing shared data at the same time.

Lock: Is an abstraction that allows at most one thread to own it. Keeping a lock is a thread that tells other threads: I'm changing this thing, don't touch it now

Two actions: Gets the ownership that allows a thread to acquire a lock . If a thread attempts to acquire a lock that is currently owned by another thread, it will block until another thread releases the lock. At this point, it competes with any other thread that is trying to acquire the lock. Only one thread can hold the lock at a time. frees ownership of a lock, allowing another thread to take ownership of it

using locks also tells the compiler and the processor that you are using shared memory at the same time to flush registers and caches to the shared storage. This ensures that the owner of the lock always views the latest data

blocking generally means that the thread waits (no longer working) until an event occurs.

Synchronization blocks and methods: Locking: locks are so common that Java provides them as built-in language features

Synchronization is built around an internal lock or monitor lock entity (The API specification typically refers to this entity simply as "Monitor"). When synchronizing: enforces exclusive access to the state of an object and establishes a happens-before relationship, both internal locks work.

each class and all its object instances have a lock, object has a lock: Object lock = new Object ();

two basic synchronization idioms : Synchronous method Synchronous Statement/synchronous code block

Synchronization statements

The synchronization statement must specify an object that provides an internal lock

The synchronization zone provides exclusive functionality: Only one thread at a time can be in the synchronization area protected by the lock of the given object. (Sequential execution)

Cases:

locks are used to protect shared data variables . If all access to data variables is protected by the same lock object (surrounded by synchronized blocks), then these accesses are guaranteed to be atomic-not interrupted by other threads

Use synchronized (obj) {...} in thread t to get the lock associated with object obj Only one thing: prevent other threads from entering the synchronized (OBJ) block until the thread T completes its synchronization block.

locks can only be guaranteed with other requests gets the thread mutex access for the same object lock. All access to data variables must be protected by the same lock. You can protect the entire set of variables behind a lock, but all modules must agree on which lock they will acquire and release

error : Lock with object automatically prevents other threads from accessing the object

Locks can only ensure mutually exclusive access to threads other than other requests that acquire the same object lock, and if other threads do not use synchronized (obj) or lock with different object, the synchronization is invalidated.

Synchronization method

When a thread invokes a synchronous method, it automatically acquires an internal lock on the method object and releases it when the method returns . Locks are released even if the return is caused by an uncaught exception.

There is no interleaving of two calls to the synchronization method on the same object.

When a thread is executing a synchronous method for an object, all other threads that invoke the same object's synchronous method block will suspend execution until the first thread completes the operation on the object.

When a synchronous method exits, it automatically establishes a happens-before relationship with the synchronization method that calls the same object later. This ensures that changes to the object state are visible to all threads

happens-before Relationship : guarantees that the write of statement a memory is visible to statement B, that is, before B begins reading the data, A has finished writing the data. Ensure memory consistency

Atomic Operation

Using volatile variables can reduce the risk of memory consistency errors, because any write to a volatile variable will create a change to the Happen-before relationship v Olatile variable with the subsequent read of the same variable. Always visible to other threads (faster)

Rationale: each time such variable is used to read in main memory , and when the member variable changes , forcing the thread to write the change value back to the shared memory . So at any moment, two different threads always see the same value for a member variable. Avoid the use of register cache optimizations for virtual machines (threads can store variables in local memory, such as a machine's register) , rather than read and write directly in main storage. This can cause a thread to modify the value of one variable in main memory, while another thread continues to use its copy of the variable value in the register, resulting in inconsistent data .

Volatile cannot handle all cases

Volatile does not provide the necessary atomic properties and can only be used in a limited number of cases to replace the lock with a volatile variable: the write operation on the variable does not depend on the current value, and the valid value of the variable is independent of the state of any program, including the current state of the variable.

Can synchronized be used in all places? No

Synchronization is expensive for programs, and because you need to acquire locks (and flush the cache and communicate with other processors), it can take longer to make synchronous method calls

When you don't need to sync, don't use it. The synchronous method means that you are acquiring a lock, regardless of which lock it is, or whether it is the correct lock to protect the shared data access that you will perform.

When synchronized is synchronized to a method, only one thread can be called at a time , and if other threads want to run on a different buffer, the buffers should be secure, and they will still be blocked until single lock is released , the performance loss is serious.

A deadlock describes a situation in which two or more threads are always blocked, waiting for each other.
one way to prevent deadlocks is to ① the locks that need to be acquired at the same time, and to ensure that all code acquires locks in that order

② a coarse-grained lock that monitors multiple object instances with a single lock (in the worst case, the program may be executed essentially sequentially, with loss of concurrency.) )

Starvation describes a situation in which a thread cannot gain access to a shared resource without making progress.

This happens when a shared resource is caused by a "greedy" thread that is not available for a long time.

For example, suppose an object provides a synchronous method that often takes a long time to return. If a thread calls this method frequently, other threads also need to frequently synchronize access to the same object Live Lock: If the behavior of one thread is also a response to the behavior of another thread, it can result in a live lock. as with deadlocks, the live lock thread is unable to make further progress, the threads are not blocked, and they are only busy responding to the other person's recovery efforts. Thread.Sleep (Time) lets the current thread pause execution for a specified periodThe Join () method is used to maintain the execution of the currently running thread until the thread dies (execution is complete) before the subsequent thread can continue (let one thread wait for the other thread to end. (The output of the preceding thread may be required as input))

After wait () is executed, the current thread waits until another thread calls the Notify () method of this object or the Notifyall () method.

At some point in the future, another thread will get the same lock and call Object.notifyall (), notifying all threads waiting for the lock that an important event has occurred. after the second thread releases the lock for a period of time, the first thread acquires the lock again and returns from the waiting call

Low-level interruptible blocking method: Thread.Sleep (), Thread.Join (), or object.wait ()

Blocking method: The general method of completion depends only on what it wants to do, and whether there are enough compute resources available, and the completion of the blocking method depends on some external events, such as timer expiry, I/O completion, or another thread's action (releasing a lock, setting a flag, Or put a task in a work queue). The general approach ends when their work is done, and the blocking methods are more difficult to predict because they depend on external events. Blocking methods can affect responsiveness because it is difficult to predict when they will end. Blocking methods can be useful because they cannot be terminated because they cannot wait for the event to wait for them to be canceled.

Interrupt ()

One of the following two scenarios occurs when another thread breaks a thread by calling Thread.Interrupt ().

① if the interrupted thread is executing a low-level interruptible blocking method, such as Thread.Sleep (), Thread.Join (), or object.wait (), then it will unblock and throw interruptedexception.

②interrupt () Just sets the interrupt state of the thread.

The interrupt state can be read by thread.isinterrupted () and can be read and purged by an operation called thread.interrupted ()

A break is a polite request to another thread to stop what it is doing when it is willing and convenient.

Security (incorrect calculation)

Activity (no calculation)

Software constructs concurrent 3 (thread safety)----locking and synchronizing

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.