preface

This series of blog posts is a summary of Concurrent Programming in Java. Lol, terminology is a collection of terms and terminology used to represent concepts in a particular academic domain, also known in our country as a noun or technical term (as distinct from terminology used in grammar). Terms are contractual linguistic symbols that express or define scientific concepts by voice or text and are tools for communication of ideas and knowledge. Let me explain these terms to you in vernacular.

Thread safety

What is thread safety? This is a platitude, I believe you have encountered in the process of interview, in the definition of thread safety, the most core concept is correctness, if the definition of thread safety is vague, then it is the lack of a clear definition of correctness. Correctness means that the behavior of a class is completely consistent with its specification. In a good specification, various invariance conditions are usually defined to constrain the state of the object, and various posterior conditions are defined to describe the results of the operation of the object. In plain English, a class that executes correctly in either a single-threaded or multi-threaded environment is thread-safe. Threading is not safe if it leads to unexpected results in the process of alternating threads.

visibility

So if you have a variable, and now you’re reading or writing to it, visibility is whether or not the current thread’s writing to that variable is visible to other threads, whether or not other threads know that you’ve changed that variable. If visibility is not guaranteed, a synchronization mechanism must be used. Otherwise, when another thread reads the variable, it may get an invalid value. This value is called invalid data. Note that for non-volatile long and double, the JVM allows a 64-bit read or write to be split into two 32-bit reads. When reading a non-volatile long, if the read or write is performed on a different thread, It is possible to read the high 32 bits of one value and the low 32 bits of another, so it is not safe to use variables such as shared mutable longs and doubles in a multithreaded environment unless they are declared with the keyword volatile or protected by locks.

  1. Now for Volatile:

The Java language provides a weaker synchronization mechanism, the volatile type, to ensure that updates to variables are notified to other threads. Use the variable as volatile. In THE JMM, communication between threads is implemented using shared memory. The memory semantics of volatile are:

  • When a volatile variable is written, the JMM immediately flusher the value of the shared variable from the thread’s local memory to main memory.
  • When a volatile variable is read, the JMM invalidates the thread’s local memory and reads the shared variable directly from main memory.
  1. Conditions for use of volatile:
  • Writes to variables do not depend on the current value of the variable, or you can ensure that only a single thread updates the value of the variable.
  • This variable will not be included in the invariance condition along with other state variables.
  • No locks are required to access variables.

Locking ensures both visibility and atomicity, whereas volatile variables only ensure visibility and should never be used to ensure atomicity.

Release and escape

Publishing an object means making it available to code outside of the current scope, for example, by saving a reference to it somewhere other code can access, or by returning it in a non-private method, or by passing a reference to another class method. When an object is published that should not be published, the situation is called escape.

Thread closed

Synchronization is often used when accessing shared mutable data. One way to avoid synchronization is to share data differently. If data is accessed only within a single thread, synchronization is not required. This technique is called thread closure, and it is one of the simplest ways to achieve thread-safety. Several thread closing techniques are described below.

  1. Ad-hoc threads are closed

    Ad-hoc thread closure refers to the fact that the responsibility for maintaining thread closure is entirely assumed by the program implementation. Such as visibility modifiers or local variables that can seal an object to the target thread. In fact, thread-closed objects are usually stored in common variables. Ad-hoc thread blocking is very fragile, so use it sparingly in your program, using two techniques (stack blocking, ThreadLocal).

  2. The stack is closed

    Stack closure, also known as intra-thread or thread-local, not to be confused with ThredaLocal, is easier to maintain and more robust than ad-hoc. In a stack closure, objects can only be accessed through local variables.

Public void test(){// define a variable Set Set; // Instantiate a TreeSet object and save a reference to it in set. set = new TreeSet(); }Copy the code

The TreeSet object is then enclosed in local variables and, therefore, in the thread of execution, in the thread of execution’s stack, inaccessible to other threads.

  1. ThreadLocal

    A more formal approach to maintaining thread closure is to use ThreadLocal. This class associates a value in a thread with the object that holds the value. ThreadLocal provides access interfaces or methods such as GET and set that hold a separate copy for each thread that uses the variable. So GET always returns the latest value set by the current thread when it executes the set. ThreadLocal is typically used to prevent the sharing of singleton or global variables with mutable objects.

Public static ThreadLocal<Connection> connectionThreadLocal = new ThreadLocal<Connection>(){@override protected Connection initialValue() { return DriverManager.getConnection(DB_URl); }}; / / each thread directly get when using public static Connection getConnection () {return connectionThreadLocal. The get (); }Copy the code

invariance

An object is immutable if its state cannot be changed after it is created, and thread-safety is one of the inherent properties of immutable objects. An object is immutable if:

  • The state of an object cannot be modified after it is created.
  • All fields of the object are of final type.
  • The object was created correctly (the this reference did not escape during object creation)

Final field: Used to construct immutable objects. Fields of final type cannot be modified (although the objects referenced by a final field can be modified if they are mutable). In the Java memory model, however, final fields have special semantics. Final fields ensure the security of the initialization process, allowing unrestricted access to immutable objects and no synchronization when they are shared.

Security issued

  1. To safely publish an object, references to the object and its state must be visible to other threads at the same time. A properly constructed object can be safely published in the following ways:
  • Initializes an object reference in a static initialization function.
  • Save a reference to the object in a volatile field or Atomicreferance object.
  • Save a reference to an object in the final type field of a properly constructed object.
  • Saves a reference to an object into a lock protected domain.
  1. There are some useful strategies to use when using and sharing objects in concurrent programs:
  • Thread-closed: Thread-closed objects can only be owned by one thread, are enclosed in that thread, and can only be modified by that thread
  • Read-only shares: A shared read-only object can be accessed concurrently by multiple threads without additional synchronization, but cannot be modified by any thread. Shared read-only objects include immutable objects and de facto immutable objects.
  • Thread-safe sharing: Thread-safe objects are synchronized internally so that multiple threads can access the object through its public interface without further synchronization.
  • Protected objects: Protected objects can only be accessed by holding a specific lock. Protected objects include objects encapsulated in other thread-safe objects, as well as published objects protected by a specific lock.

After you look at the hard point like point attention oh! Check out my homepage for more blogs. Please correct any mistakes.