Shared objects "Java Concurrency combat" the

Foreword

  This series of blog is a little "Java Concurrency in combat," summarized herein, this mainly on the following content, the content would be more boring. You may not be able to see the title intuitive feeling that in the end what it meant, that's jargon, ha ha, next to explain the terms (terminology) is used in a particular subject area indicate the title of a collection of concepts, in our country, also known as a noun or technology noun (different from the grammar of nouns). The term is used to express agreement or limited language symbol of scientific concepts by voice or text, is the exchange of ideas and knowledge tools. I use the vernacular to explain to you under these terms.

Thread Safety

  What is thread safe? This is regarded as a common problem, I believe we have encountered in the course of the interview, in a thread-safe definition, the core concept is correctness, if the definition of thread safety is fuzzy, so is the lack of proper clearly defined nature. Correctness meaning, a class of its behavior specification exactly typically define the various conditions in a well-invariant specification to constrain an object's state, and the results of the various definitions experimental conditions described operation of the object. It means either a class or a multi-threaded environment can be performed correctly in a single-threaded environment, then this class is thread-safe. If the cause unpredictable results during alternate execution thread, then the thread is unsafe.

Visibility

  If there is a variable, it is now read and write operations, visibility say is the current thread variable write operation is visible to other threads, other threads can not know that you made changes to this variable. If you can not guarantee visible, you must use the synchronization mechanism. Otherwise, when the other threads to read this variable, may get a value has failed. This value is called invalid data.
  Remind here, for non-volatile types of long and double variables JVM allows 64-bit read or write operation into two 32-bit operation, when reading a non-volatile long variable type, if the operation is a read and write when executed in a different thread, then it may be read to the low 32 high a value of 32 and another value, so use the shared variable and other types of long and double variables in multithreaded environment do not safe, unless the volatile keyword to declare them, or protected by a lock.

  1. Now introduce Volatile: Java language provides a weaker synchronization mechanism, namely volatile type, to ensure that the update notification variables to other threads. Use is in front of the variable to add volatile. In JMM, the communication between threads using shared memory to achieve. volatile memory semantics:
  • When writing a volatile variable, JMM will correspond to the thread local memory shared variable values, flushed to main memory immediately.
  • When reading a volatile variable, the thread will JMM corresponding local memory is disabled, the shared variable is read directly from main memory.
  1. volatile conditions of use:
  • Writes to variables do not depend on the current value of the variable, or you can ensure that only a single thread to update the value of the variable.
  • This variable will not be included invariance conditions along with other state variables.
  • When accessing the variable does not need to be locked.

加锁机制既可以确保可见性又可以确保原子性,而volatile变量只能确保可见性,千万不要用它来确保原子性操作。

Release and escape

Publish an object means that the objects can be used in your code outside the current scope, for example, to a point where the object is saved to other reference code can access or return in one of the non-private methods reference or references to other classes transfer process. When an object should not publish was released, this is called the escape.

Thread closed

When accessing the variable data sharing often necessary to use sync. One way to avoid the use of synchronous way is different shared data, if only in a single-threaded data access, synchronization is not required, this technique is called a thread closed, it is an implementation of thread safety easiest way. Here are some thread sealing technique.

  1. Ad-hoc thread closed

    Ad-hoc thread closure means, maintenance thread closure of a program to achieve full responsibility to bear. For example visibility modifier or local variables, objects capable of closing onto a target thread. In fact, for a thread closed objects are usually stored in the shared variable. Ad-hoc thread closure is very fragile, so the program to make use of it less, you can use the following two techniques (closed stacks, ThreadLocal).

  2. Stack closed

    Stack closure also known as internal threads or thread-local use, not to be confused with ThredaLocal, than Ad-hoc easier to maintain, and more robust. In a closed stack, the objects can only be accessed by local variables.

//伪代码
public void test(){
//定义一个变量
Set set ;
// 实例化一个TreeSet对象,并将该对象的一个引用保存到set中。
set = new TreeSet();
}
复制代码

Such TreeSet object is enclosed in a local variable, it is also close to the execution thread, which is located in executing thread stack, other threads can not access the stack.

  1. ThreadLocal

    Method of maintaining a closed thread is more standardized use ThreadLocal, this class can associate a value with the value stored in the thread like, ThreadLocal provides get and set such as access interfaces or methods that is each use of the variable thread there a separate copy, so get always returns the latest value set by the current thread execution set. ThreadLocal commonly used to prevent a single instance of a variable or global variables shared image.

   //保存一个数据库连接对像
   public static ThreadLocal<Connection> connectionThreadLocal = 
   new ThreadLocal<Connection>(){
       @Override
       protected Connection initialValue() {
           return DriverManager.getConnection(DB_URl);
       }
   };
   //每个线程使用时直接get
   public static Connection getConnection(){
       return connectionThreadLocal.get();
   }
复制代码

Invariance

If one of the state as it can not be modified after it is created, then the object is immutable, thread-safe sex is one of the inherent properties are not changed object. When satisfied about the conditions, the object is immutable:

  • After the object is created its status can not be changed.
  • All fields are final type of object.
  • Objects are created correctly (during the creation of the object, this reference is no escape)

Final fields: configuration for immutable objects. final type of field can not be modified (but if the object referenced by the final field is variable, then these references can be modified objects). However, in the java memory model, final fields as well as a special semantics. final field safety can be ensured initialization process, thereby unrestricted access immutable objects, and these need not synchronize shared objects.

Security release

  1. To publish a security object reference to the object, and the object's state must be visible to other threads, a properly constructed objects can be safely released in the following ways:
  • Initialize an object reference in a static initialization function.
  • The reference object is stored to volatile types of field or Atomicreferance object.
  • The reference to the object saved to a properly constructed object final type field.
  • The object reference is saved to a domain protected by a lock.
  1. When used and shared objects in concurrent programs, you can use some practical strategies:
  • Thread closed : Thread closed objects can only be owned by a thread, the object is enclosed in this thread, and can only be modified by this thread
  • Read-only shared : without additional synchronization, the shared object can be read only concurrent access by multiple threads, but any thread can not modify it, read-only shared objects include objects and immutable facts immutable objects.
  • Share thread safety : Thread-safe objects in its internal synchronization, so multiple threads can be accessed through the object's public interface without further synchronization.
  • Object of protection : the protected object can only be accessed through the locks held particular, the protection of other objects including packaging objects in a thread-safe objects, and objects published and protected by a specific lock.

After a hard point you can see it like a focus point oh! View profile, there are more blog Oh. If wrong, please correct me. AC plus interest group together.

Guess you like

Origin juejin.im/post/5d58d81551882521872b97e3