-
The wait/notify must exist in the synchronized block.
-
Volatile
Multi-threaded memory model: Main Memories (memory), working memory (line stacks), when processing data, the thread will load the value from memory to the local stack, complete operation and then save back ( The role of volatile keywords: every action against the variable fires a load and save
-
The thread class best practice: When writing, it is best to set the thread name Thread.Name, and set the thread group Threadgroup, to facilitate management. In the event of a problem, the print line stacks (jstack-pid) can see at a glance which thread is out of the question, what the thread is doing.
-
How to get exceptions in threads
Thread t = new thread (Task);
T.setuncaughtexception (New Uncaughtexceptionhandler () {...});
T.start ();
You cannot use Try,catch to get exceptions in a thread
-
Future and Futuretask
The future is the interface, Futuretask is the class
The future represents the result of an asynchronous computation. Asynchronous computations are performed on other threads, so the results of an asynchronous calculation may have values or may not have values. As a result, the future provides some way to deal with this unknown state:
A. IsDone () Whether the asynchronous task is complete, that is, no result
B. Get () Gets the asynchronous task result and if the asynchronous task is not completed, this method will block until the Async method completes or the task is canceled (the Cancel () method is called)
C. Cancel () cancels the asynchronous task if the asynchronous task has completed, then the cancel fails (that is, the Cancel () method returns false)
D. iscancelled () query whether the asynchronous task has been canceled
Futuretask is an asynchronous task that can be canceled, Futuretask implements two interfaces, runnable and future, so it can be executed as runnable by the thread, and can be used as the future to get the callable return value. So what are the benefits of using this combination? Assuming that there is a time-consuming return value that needs to be computed, and that the return value is not immediately required, then this combination can be used to compute the return value with another thread, and the current thread can do other things before the return value is needed, and then through the future.
//1futuretask<integer> future = new futuretask<object> (callable); New Thread (Future). Start (); There are other things you can do Future.get ();//block get result//2public void function () {//1. Init Services Final Executorservice Executorse Rvice = ...//2. Make task futuretask<string> futuretask = new futuretask<string> (new callable<string> () {@Ove Rride public String Call () throws Exception {string result = ""; Do something; return result; } }); 3. Submit Task Executorservice.submit (Futuretask); 4. Get result String result = Futuretask.get (); 5. Do something with result//...}
-
Threadlocal class
Useful: Saves the thread's independent variables. For a thread class (inherited from thread) when you use threadlocal to maintain variables, Threadlocal provides a separate copy of the variable for each thread that uses the variable, so each thread can independently change its own copy without affecting the copy of the other thread. Commonly used in user Login control, such as recording session information.
Implementation: Each thread holds a variable of type Treadlocalmap (the class is a lightweight map, the same as map, the difference is that the bucket is placed in the entry rather than the entry list. function is also a map. ) takes itself as key and targets as value. The primary method is get () and set (T a), and a is returned when the set is maintained in map with a threadlocal-a,get. The threadlocal is a special container.
-
and contract: Atomic class, Lock class, container class, management class summary
and contract Summary 1
and contract Summary 2
-
CAS and ABA
CAS: For a certain value in memory V, provide an old value A and a new value, B. If the supplied old value V and a are equal, write B to v. This process is atomic in nature.
The result of the CAs execution either succeeds or fails, and the next class uses constant retries for the failed scenario. or give up.
ABA: If another thread modifies the V-value assumption that it was a, first modify it to B, and then modify it back to a. The current thread's CAS operation cannot tell if the current V value has changed.
How to solve the ABA problem? Typically, you use a version stamp to solve this problem and avoid problems in concurrency. CAS is an optimistic locking technique
-
Reorder/happens before
JMM, if the result of one operation needs to be visible to another, there must be a happens-before relationship between the two operations. The
Happen-before principle is a very important principle in jmm, which is the main basis for judging whether the data is competitive or not, and ensures the visibility in the multi-threaded environment. The
Happen-before principle solves multi-threaded operation problems caused by reordering.
If there is a happens-before relationship between the two operations, the result of the previous operation is visible to the subsequent operation.
Happens-before principle Rules:
- Program order rules: Within a thread, in code order, the preceding operations occur in the previous operation;
- Locking rule: A unlock operation first occurs after the face of the same lock amount lock operation;
- volatile variable rule: a write to a variable takes precedence over a read operation that precedes the variable;
- Pass rule: If action a precedes action B , and Operation B occurs first in Operation C, you can conclude that operation a precedes operation C;
- thread start rule: the Start () method of the thread object takes precedence over each action of this thread;
- thread break rule: Thread interrupt The invocation of the () method first occurs when the code of the interrupted thread detects the occurrence of the interrupt event, and the
- thread terminates the rule: all operations in the thread occur first in the thread's termination detection, we can end with the Thread.Join () method, Thread.isalive () The return value means that the thread has terminated execution;
- object Finalization rule: Initialization of an object occurs at the beginning of his finalize () method;
-
Thread pool
Java provides four thread pools through executors, namely:
(Cache, fixed, timed, singleton)
- Newcachedthreadpool creates a cacheable thread pool that can flexibly reclaim idle threads if the thread pool length exceeds the processing needs, and creates a new thread if it is not recyclable.
- Newfixedthreadpool creates a thread pool that controls the maximum number of concurrent threads, and the excess threads wait in the queue.
- Newscheduledthreadpool creates a fixed-line pool that supports timed and recurring task execution. (This is recommended for scheduled tasks, do not use timertask because: abnormal exit all Tasks)
- Newsinglethreadexecutor creates a single threaded thread pool that performs tasks with only a single worker thread, ensuring that all tasks are executed in the specified order (FIFO, LIFO, priority).
-
Reference documents
Document 1-Concurrent multithreading
Document 2-Concurrent Programming Guide
Literature 3-aqs
Literature 4-concurrenthashmap