当前位置:网站首页>Learning notes on futuretask source code of concurrent programming series
Learning notes on futuretask source code of concurrent programming series
2022-07-01 22:31:00 【51CTO】
Concurrent programming series FutureTask Source learning notes
1、 What is? FutureTask class ?
In the study of the previous chapter , We know Future Basic usage of class , got it Future In fact, it is to monitor the execution of thread tasks , Then this blog continues to learn FutureTask. Then what is FutureTask class ?
Future yes 1.5 The top-level abstract interface of asynchronous programming introduced by version ,FutureTask It is Future The basic implementation class of . meanwhile FutureTask It's also achieved Runnable Interface , therefore FutureTask Can also be used as a independent Runnable Mission .
2、 Use FutureTask encapsulation Callable Mission
It cannot be passed in directly in the thread Callable Mission , So we need to use FutureTask,FutureTask It can be used to encapsulate Callable Mission , Here is an example :
package com.example.concurrent.future;
import java.util.Random;
import java.util.concurrent.*;
/**
* <pre>
* FutureTask Example
* </pre>
* <p>
* <pre>
* @author nicky.ma
* Modify the record
* Revised version : Modifier : modification date : 2021/08/28 18:04 Modify the content :
* </pre>
*/
public class FutureTaskExample {
public static void main(String[] args) throws ExecutionException, InterruptedException {
FutureTask futureTask = new FutureTask(new CallableTask());
Thread t = new Thread(futureTask);
t.start();
System.out.println(futureTask.get());
}
static class CallableTask implements Callable<Integer> {
@Override
public Integer call() throws Exception{
Thread.sleep(1000L);
return new Random().nextInt();
}
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
3、FutureTask UML Class diagram
Turn down FutureTask Source code , It can be seen that RunnableFuture Interface
RunnableFuture How is the interface ? It can be seen that it actually inherited Runnable,Future
stay idea Draw in FutureTask Of uml Class diagram :

Insert picture description here
therefore , so to speak FutureTask It's essentially a Runnable Mission
4、FutureTask Source code learning
- FutureTask Class properties
public class FutureTask<V> implements RunnableFuture<V> {
// state : There are the following 7 Medium state
private volatile int state;
// newly build
private static final int NEW = 0;
// The task is being completed
private static final int COMPLETING = 1;
// Task completed normally
private static final int NORMAL = 2;
// The task is abnormal
private static final int EXCEPTIONAL = 3;
// Task to cancel
private static final int CANCELLED = 4;
// Task interrupted
private static final int INTERRUPTING = 5;
// Task interrupted
private static final int INTERRUPTED = 6;
// Support the returned results Callable Mission
private Callable<V> callable;
// Task execution results : Contains normal and abnormal results , adopt get Method to get
private Object outcome;
// Task execution thread
private volatile Thread runner;
// Wait queue for stack structure , This node is the topmost node in the stack
private volatile WaitNode waiters;
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- Construction method
// Pass in callable Mission
public FutureTask(Callable<V> callable) {
if (callable == null)
throw new NullPointerException();
this.callable = callable;
this.state = NEW; // ensure visibility of callable
}
// Pass in runnable Mission 、 Outcome variable result
public FutureTask(Runnable runnable, V result) {
this.callable = Executors.callable(runnable, result);
this.state = NEW; // ensure visibility of callable
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- It's a Runnable Mission ,run Method realization
public void run() {
// Two situations return directly to
// 1: State is not NEW, The instructions have been executed , Get the cancelled task , Go straight back to
// 2: Status is NEW, Save the current execution thread in runner Field (runnerOffset) in , If the assignment fails , Go straight back to
if (state != NEW ||
!UNSAFE.compareAndSwapObject(this, runnerOffset,
null, Thread.currentThread()))
return;
try {
Callable<V> c = callable;
if (c != null && state == NEW) {
V result;
boolean ran;
try {
// Performed the given Callable Mission
result = c.call();
ran = true;
} catch (Throwable ex) {
result = null;
ran = false;
// Abnormal condition , Set the abnormal
setException(ex);
}
if (ran)
// The task is performed normally , Set result
set(result);
}
} finally {
// runner must be non-null until state is settled to
// prevent concurrent calls to run()
runner = null;
// state must be re-read after nulling runner to prevent
// leaked interrupts
int s = state;
// The task was interrupted , Execute interrupt handling
if (s >= INTERRUPTING)
handlePossibleCancellationInterrupt(s);
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
setException Method :
protected void setException(Throwable t) {
// CAS, Change the status from NEW Change it to COMPLETING( In the middle )
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
// Return results
outcome = t;
// Change the state to EXCEPTIONAL
UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
finishCompletion();
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- get Get execution results
get Timeout method
public V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
// unit It's the time unit , Must pass
if (unit == null)
throw new NullPointerException();
int s = state;
// Blocking time exceeded timeout, Throw out TimeoutException
if (s <= COMPLETING &&
(s = awaitDone(true, unit.toNanos(timeout))) <= COMPLETING)
throw new TimeoutException();
return report(s);
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
Focus on awaitDone Method :
private int awaitDone(boolean timed, long nanos)
throws InterruptedException {
// Calculate the deadline
final long deadline = timed ? System.nanoTime() + nanos : 0L;
WaitNode q = null;
//
boolean queued = false;
// Infinite loop , Judge whether the conditions meet
for (;;) {
// 1、 Whether the thread is interrupted , Yes, the situation , Remove node , Throw at the same time InterruptedException
if (Thread.interrupted()) {
removeWaiter(q);
throw new InterruptedException();
}
// 2、 Get current status , If the state is greater than COMPLETING
// It means the task is done , It is possible to complete the normal execution , Or you may cancel the task
int s = state;
if (s > COMPLETING) {
if (q != null)
// thread Set as null wait for JVM gc
q.thread = null;
// Return results
return s;
}
//3、 If the state is in the middle COMPLETING
// Indicates that the task has ended, but the task execution thread has not had time to give outcome assignment
else if (s == COMPLETING) // cannot time out yet
// In this case, threads yield Give up the right of execution , Execute... For other threads first
Thread.yield();
// 4、 If the waiting node is empty , Then construct a waiting node
else if (q == null)
q = new WaitNode();
// 5、 If you haven't queued yet , Then add the current node to waiters The first node and replace the original node waiters
else if (!queued)
queued = UNSAFE.compareAndSwapObject(this, waitersOffset,
q.next = waiters, q);
else if (timed) {
nanos = deadline - System.nanoTime();
// If you need to wait for a specific time , Then calculate the waiting time first
// If it's over time , Delete the corresponding node and return to the corresponding status
if (nanos <= 0L) {
removeWaiter(q);
return state;
}
// Block waiting for a specific time
LockSupport.parkNanos(this, nanos);
}
else
// Let thread wait , Block the current thread
LockSupport.park(this);
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
- 40.
- 41.
- 42.
- 43.
- 44.
- 45.
- 46.
- 47.
- 48.
- 49.
- 50.
- 51.
- 52.
- cancel Cancel the task
public boolean cancel(boolean mayInterruptIfRunning) {
// If the mission is over , Then return directly false
if (!(state == NEW &&
UNSAFE.compareAndSwapInt(this, stateOffset, NEW,
mayInterruptIfRunning ? INTERRUPTING : CANCELLED)))
return false;
try { // in case call to interrupt throws exception
// Situations where tasks need to be interrupted
if (mayInterruptIfRunning) {
try {
Thread t = runner;
// Calling thread's interrupt To stop the thread
if (t != null)
t.interrupt();
} finally { // final state
// Change the status to INTERRUPTED
UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED);
}
}
} finally {
finishCompletion();
}
return true;
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
finishCompletion Method :
private void finishCompletion() {
// assert state > COMPLETING;
for (WaitNode q; (q = waiters) != null;) {
if (UNSAFE.compareAndSwapObject(this, waitersOffset, q, null)) {
// Infinite loop , Traverse waiters list , Wake up the thread in the node , And then Callable Set as null
for (;;) {
Thread t = q.thread;
if (t != null) {
q.thread = null;
// Wake up the thread
LockSupport.unpark(t);
}
WaitNode next = q.next;
if (next == null)
break;
// Set as null, Give Way JVM gc
q.next = null; // unlink to help gc
q = next;
}
break;
}
}
done();
callable = null; // to reduce footprint
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
边栏推荐
- MySQL清空表数据
- In the past 100 years, only 6 products have been approved, which is the "adjuvant" behind the vaccine competition
- 按照功能对Boost库进行分类
- MQ learning notes
- linux下清理系统缓存并释放内存
- [STM32] stm32cubemx tutorial II - basic use (new projects light up LED lights)
- Training on the device with MIT | 256Kb memory
- CNN卷积神经网络原理讲解+图片识别应用(附源码)[通俗易懂]
- Redis配置与优化
- Is PMP certificate really useful?
猜你喜欢

详解LockSupport的使用

News classification based on LSTM model

91.(cesium篇)cesium火箭发射模拟
![[intelligent QBD risk assessment tool] Shanghai daoning brings you leanqbd introduction, trial and tutorial](/img/ac/655fd534ef7ab9d991d8fe1c884853.png)
[intelligent QBD risk assessment tool] Shanghai daoning brings you leanqbd introduction, trial and tutorial

业务可视化-让你的流程图'Run'起来

"The silk road is in its youth and looks at Fujian" is in the hot collection of works in the Fujian foreign youth short video competition

keras训练的H5模型转tflite

名单揭晓 | 2021年度中国杰出知识产权服务团队

并发编程系列之FutureTask源码学习笔记

Training on the device with MIT | 256Kb memory
随机推荐
Can you get a raise? Analysis on gold content of PMP certificate
String类型转换BigDecimal、Date类型
IDA动态调试apk
AirServer2022最新版功能介绍及下载
[noip2013] building block competition [noip2018] road laying greed / difference
Qtreeview+qabstractitemmodel custom model: the third of a series of tutorials [easy to understand]
Case of camera opening by tour
require与import的区别和使用
Chapter 9 Yunji datacanvas company has been ranked top 3 in China's machine learning platform market
Which securities company should we choose to open an account for flush stock? Is it safe to open an account with a mobile phone?
详解JMM
Sonic cloud real machine learning summary 6 - 1.4.1 server and agent deployment
In the past 100 years, only 6 products have been approved, which is the "adjuvant" behind the vaccine competition
linux下清理系统缓存并释放内存
工控设备安全加密的意义和措施
Use of vscode
Business visualization - make your flowchart'run'up
灵动微 MM32 多路ADC-DMA配置
JS how to get a list of elements in a collection object
Count the number of each character in the character