Summary of three confusing keywords in Java multithreaded programming

  • 2020-04-01 03:43:53
  • OfStack

An overview of the

Recently In the "ThinKing In Java", see the multi-threading chapter feel that there are some concepts are easy to confuse it is necessary to summarize, although not new things, but still very important, very basic, In the development or reading the source code often encountered, here is a simple summary.

1. The volatile

Volatile is primarily used to synchronize variables in multiple threads.
In general, to improve performance, each thread will keep a copy of the variables in main memory in its own memory as a copy of the variables at run time, but it is easy to see that the variables stored in multiple threads are inconsistent or inconsistent with the values of the variables in main memory.
And when a variable is a volatile after modification, the variable thread cannot be cached in memory, it tells the compiler don't undergo any out of read and write operation optimization, in other words, there is no different from the "main" memory area variables of copy, so when the variables are changed, all calls thread will get the same value of the variable, this ensures that the variable visibility in the application (when a task made changes in the application must be visible), the performance also corresponding reduced (or higher than synchronized).
Note that volatile only ensures that the same block of memory is being manipulated, not that the operation is atomic. So volatile is typically used to declare simple type variables, making them atomic, so that some simple assignment or return operation is guaranteed to be uninterrupted. But volatile loses its effect when the value of the variable is determined by its previous value, as determined by the nature of the volatile keyword.
So be careful not to assume that all operations on volatile variables are atomic operations and that the synchronized keyword is no longer needed.

2. The ThreadLocal

First ThreadLocal and local Thread without a dime relationship, more is not a special Thread, it is just a Thread in the local variables (is actually a Map), ThreadLocal will use the variable for each Thread to provide a copy of the independent variables, so each Thread can independently to change your copy, and will not affect the other threads of the copy. This is a space-for-time approach (as opposed to synchronized), which costs memory, greatly reduces the performance cost of thread synchronization (such as synchronized), and reduces the complexity of thread concurrency control.
In my opinion, a typical example is the use of ThreadLocal in the Android source code of Looper, which also contains the basic usage of ThreadLocal. The specific code is as follows:


public class Looper { 
private static final String TAG = "Looper";

// sThreadLocal.get() will return null unless you've called prepare(). 
private static final ThreadLocal sThreadLocal = new ThreadLocal(); 

...... 

private static Looper mMainLooper = null; 

...... 

public static final void prepare() { 
  if (sThreadLocal.get() != null) { 
    throw new RuntimeException("Only one Looper may be created per thread"); 
  } 
  sThreadLocal.set(new Looper()); 
} 

...... 

public static final void prepareMainLooper() { 
  prepare(); 
  setMainLooper(myLooper()); 

  ...... 

} 

private synchronized static void setMainLooper(Looper looper) { 
  mMainLooper = looper; 
} 
public synchronized static final Looper getMainLooper() { 
  return mMainLooper; 
} 

...... 

public static final Looper myLooper() { 
  return (Looper)sThreadLocal.get(); 
} 

...... 

} 


It is important to note, however, that while both ThreadLocal and Synchonized are used to handle concurrent access by multiple threads, ThreadLocal is fundamentally different from synchronized. Synchronized is a mechanism that makes use of locks so that a variable or block of code should be accessed by only one thread at a time. ThreadLocal provides a copy of the variable for each thread, so that each thread does not access the same object at any given time, thus isolating the data Shared by multiple threads. Synchronized, on the other hand, is used to enable data sharing when multiple threads communicate. That is, Synchronized is used for data sharing between threads, and ThreadLocal is used for data isolation between threads. So ThreadLocal is not a substitute for synchronized, which has a broader scope (synchronization).

3. The synchronized

The synchronized keyword is automatically implemented by Java using the lock mechanism and is commonly used in both synchronized methods and synchronized code blocks. Java automatically containing all the objects in a single lock (also known as monitor), when the call object on its arbitrary synchronized method, the object is locked (a task can obtain the object lock, counter will increase), at the same time in a thread before returning from this method, the object in all of the other to call class is marked as a synchronized method of thread will be blocked. Of course there is also a lock for each Class (as part of the Class object), so you get the idea ^.^.
Finally, it is important to note that synchronized is one of the safest methods of synchronization. Any other method is risky and of course most costly.


Related articles: