当前位置:网站首页>ThreadLocal&Fork/Join
ThreadLocal&Fork/Join
2022-07-25 13:10:00 【Who makes perfect -lwp】
ThreadLocal
One 、 Solve thread security issues .
Two 、ThreadLocal Principle
set() Within the scope of the current thread , Set a value to store in ThreadLocal in , This value is only visible to the current thread . It is equivalent to establishing a copy within the scope of the current thread .
get() Remove from the scope of the current thread set Value set by method .
remove() Remove the value stored in the current thread
withInitial java8 Initialization method in
If the current value corresponds to entry Array key by null, Then the method will look forward to find that there are still key Invalid entry, Clean up . Through linear exploration , solve hash The question of conflict .
3、 ... and 、ThreadLocal actual combat
package com.gupaoedu.concurrent;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Gupao College , Just for better you
* Gupao College -Mic: 2082233439
* http://www.gupaoedu.com
**/
public class ThreadLocalDemo {
// Non thread safe
private static final SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private static ThreadLocal<DateFormat> dateFormatThreadLocal=new ThreadLocal<>();
private static DateFormat getDateFormat(){
DateFormat dateFormat=dateFormatThreadLocal.get(); // Get a... From the scope of the current thread DateFormat
if(dateFormat==null){
dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//Thread.currentThread();
dateFormatThreadLocal.set(dateFormat); // To set a... Within the scope of the current thread simpleDateFormat object .
}
return dateFormat;
}
public static Date parse(String strDate) throws ParseException {
return getDateFormat().parse(strDate);
}
public static void main(String[] args) {
ExecutorService executorService= Executors.newFixedThreadPool(10);
for (int i = 0; i < 20; i++) {
executorService.execute(()->{
try {
System.out.println(parse("2021-05-30 20:12:20"));
} catch (ParseException e) {
e.printStackTrace();
}
});
}
}
}

Four 、 Memory leaks :
Through the above analysis , We know expungeStaleEntry() The way is to help recycle , According to the source code , We can find out get and set Methods can trigger cleanup methods expungeStaleEntry(), So under normal circumstances, there will be no memory overflow But if we don't call get and set You may be faced with a memory overflow , Make a good habit of calling when you no longer use it remove(), Speed up garbage collection , Avoid memory overflow
Step back , Even if we don't call get and set and remove Method , At the end of the thread , There is no strong reference pointing to ThreadLocal Medium ThreadLocalMap 了 , such ThreadLocalMap And the elements inside will also be recycled , But there is a danger that , If a thread is thread pool , It doesn't end when the thread finishes executing the code , Just return it to the thread pool , This is the time ThreadLocalMap And the elements inside will not be recycled .
Fork/Join
One 、 Work flow chart
The top-level task in the figure uses submit The method is submitted to Fork/Join In the frame ,Fork/Join Put this task into a thread to run , In the work task compute The code of the method starts on this task T1 Analyze . If the number range that the current task needs to accumulate is too large ( What is set in the code is greater than 200), Then the computing task is divided into two subtasks (T1.1 and T1.2), Each subtask is responsible for calculating half of the data accumulation , See... In the code fork Method . If the number range to be accumulated in the current subtask is small enough ( Less than or equal to 200), Just add up and return to the upper task .

Two 、ForkJoin actual combat
See the code below :

Entity class : Comment on 、 goods 、 sales 、 The store
package com.example.springbootforkjoin.pojo;
/**
* Gupao College , Just for better you
* Gupao College -Mic: 2082233439
* http://www.gupaoedu.com
* Comment information
**/
public class Comment {
private String name;
private String content;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
package com.example.springbootforkjoin.pojo;
/**
* Gupao College , Just for better you
* Gupao College -Mic: 2082233439
* http://www.gupaoedu.com
* Commodity information
**/
public class Item {
private String productName;
private int num;
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
}
package com.example.springbootforkjoin.pojo;
/**
* Gupao College , Just for better you
* Gupao College -Mic: 2082233439
* http://www.gupaoedu.com
* Sales information
**/
public class Seller {
private int totalNum;
private int sellerNum;
public int getTotalNum() {
return totalNum;
}
public void setTotalNum(int totalNum) {
this.totalNum = totalNum;
}
public int getSellerNum() {
return sellerNum;
}
public void setSellerNum(int sellerNum) {
this.sellerNum = sellerNum;
}
}
package com.example.springbootforkjoin.pojo;
/**
* Gupao College , Just for better you
* Gupao College -Mic: 2082233439
* http://www.gupaoedu.com
* Store information
**/
public class Shop {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package com.example.springbootforkjoin;
import com.example.springbootforkjoin.pojo.Comment;
import com.example.springbootforkjoin.pojo.Item;
import com.example.springbootforkjoin.pojo.Seller;
import com.example.springbootforkjoin.pojo.Shop;
/**
* Gupao College , Just for better you
* Gupao College -Mic: 2082233439
* http://www.gupaoedu.com
* Aggregated entity classes
**/
public class Context {
private Item item; // goods
private Comment comment; // Comment on
private Seller seller; // Sales information
private Shop shop; // Store information
public Item getItem() {
return item;
}
public void setItem(Item item) {
this.item = item;
}
public Comment getComment() {
return comment;
}
public void setComment(Comment comment) {
this.comment = comment;
}
public Seller getSeller() {
return seller;
}
public void setSeller(Seller seller) {
this.seller = seller;
}
public Shop getShop() {
return shop;
}
public void setShop(Shop shop) {
this.shop = shop;
}
@Override
public String toString() {
return "Context{" +
"item=" + item +
", comment=" + comment +
", seller=" + seller +
", shop=" + shop +
'}';
}
}
Corresponding service
package com.example.springbootforkjoin;
/**
* Gupao College , Just for better you
* Gupao College -Mic: 2082233439
* http://www.gupaoedu.com
**/
public interface ILoadDataProcessor {
/**
* Load the corresponding data
* @param context
*/
void load(Context context);
}
package com.example.springbootforkjoin;
import java.util.concurrent.RecursiveAction;
/**
* Gupao College , Just for better you
* Gupao College -Mic: 2082233439
* http://www.gupaoedu.com
**/
public abstract class AbstractLoadDataProcessor extends RecursiveAction implements ILoadDataProcessor{
protected Context context;
@Override
protected void compute() {
load(context); // Call the concrete implementation of the subclass
}
public Context getContext() {
this.join(); // Get an aggregated result
return context;
}
public void setContext(Context context) {
this.context = context;
}
}
package com.example.springbootforkjoin;
import com.example.springbootforkjoin.pojo.Item;
import org.springframework.stereotype.Service;
/**
* Gupao College , Just for better you
* Gupao College -Mic: 2082233439
* http://www.gupaoedu.com
**/
@Service
public class ItemService extends AbstractLoadDataProcessor{
@Override
public void load(Context context) {
Item item=new Item();
item.setNum(100);
item.setProductName(" keyboard ");
context.setItem(item);
}
}
package com.example.springbootforkjoin;
import com.example.springbootforkjoin.pojo.Comment;
import org.springframework.stereotype.Service;
/**
* Gupao College , Just for better you
* Gupao College -Mic: 2082233439
* http://www.gupaoedu.com
**/
@Service
public class CommentService extends AbstractLoadDataProcessor{
@Override
public void load(Context context) {
//RPC.
Comment comment=new Comment();
comment.setName("Mic");
comment.setContent(" The quality of the goods is very good ");
context.setComment(comment);
}
}
package com.example.springbootforkjoin;
import com.example.springbootforkjoin.pojo.Seller;
import org.springframework.stereotype.Service;
/**
* Gupao College , Just for better you
* Gupao College -Mic: 2082233439
* http://www.gupaoedu.com
**/
@Service
public class SellerService extends AbstractLoadDataProcessor{
@Override
public void load(Context context) {
Seller seller=new Seller();
seller.setSellerNum(100);
seller.setTotalNum(1000);
context.setSeller(seller);
}
}
package com.example.springbootforkjoin;
import com.example.springbootforkjoin.pojo.Shop;
import org.springframework.stereotype.Service;
/**
* Gupao College , Just for better you
* Gupao College -Mic: 2082233439
* http://www.gupaoedu.com
**/
@Service
public class ShopService extends AbstractLoadDataProcessor{
@Override
public void load(Context context) {
Shop shop=new Shop();
shop.setName(" Gupao shop ");
context.setShop(shop);
}
}
Aggregate task
package com.example.springbootforkjoin;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ForkJoinTask;
/**
* Gupao College , Just for better you
* Gupao College -Mic: 2082233439
* http://www.gupaoedu.com
**/
@Service
public class ComplexTradeTaskService extends AbstractLoadDataProcessor implements ApplicationContextAware {
ApplicationContext applicationContext;
private List<AbstractLoadDataProcessor> taskDataProcessors=new ArrayList<>();
@Override
public void load(Context context) {
taskDataProcessors.forEach(abstractLoadDataProcessor->{
abstractLoadDataProcessor.setContext(this.context);
abstractLoadDataProcessor.fork();// Create a fork task
});
}
@Override
public Context getContext() {
this.taskDataProcessors.forEach(ForkJoinTask::join);
return super.getContext();
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext=applicationContext;
taskDataProcessors.add(applicationContext.getBean(SellerService.class));
taskDataProcessors.add(applicationContext.getBean(ShopService.class));
}
}
package com.example.springbootforkjoin;
import com.example.springbootforkjoin.pojo.Item;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ForkJoinTask;
/**
* Gupao College , Just for better you
* Gupao College -Mic: 2082233439
* http://www.gupaoedu.com
*
* Represents an aggregate task
**/
@Service
public class ItemTaskForkJoinDataProcessor extends AbstractLoadDataProcessor implements ApplicationContextAware {
ApplicationContext applicationContext;
private List<AbstractLoadDataProcessor> taskDataProcessors=new ArrayList<>();
@Override
public void load(Context context) {
taskDataProcessors.forEach(abstractLoadDataProcessor->{
abstractLoadDataProcessor.setContext(this.context);
abstractLoadDataProcessor.fork();// Create a fork task
});
}
@Override
public Context getContext() {
//ForkJoinTask::join java8 Method reference
// * Construct references
// * Static method reference
// * Instance method reference
this.taskDataProcessors.forEach(ForkJoinTask::join);
return super.getContext();
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext=applicationContext;
taskDataProcessors.add(applicationContext.getBean(CommentService.class));
taskDataProcessors.add(applicationContext.getBean(ItemService.class));
taskDataProcessors.add(applicationContext.getBean(ComplexTradeTaskService.class));
}
}
Test class :
package com.example.springbootforkjoin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
/**
* Gupao College , Just for better you
* Gupao College -Mic: 2082233439
* http://www.gupaoedu.com
**/
@RestController
public class IndexController {
@Autowired
ItemTaskForkJoinDataProcessor itemTaskForkJoinDataProcessor;
@GetMapping("/say")
public Context index(){
Context context=new Context();
itemTaskForkJoinDataProcessor.setContext(context);
ForkJoinPool forkJoinPool=new ForkJoinPool();
forkJoinPool.submit(itemTaskForkJoinDataProcessor);
return itemTaskForkJoinDataProcessor.getContext();
}
}
3、 ... and 、 The demonstration effect is as shown in the figure :

Four 、 By taking a big task , Split into several small tasks , And then through fork Split ,join Aggregate , Form a completion context object , Include comments 、 Commodity information 、 Store information 、 Sales information . This code structure uses the template design pattern .
5、 ... and 、ForkJoinTask Use... When not shown ForkJoinPool.execute/invoke/submit() When the method is executed , You can also use your own fork/invoke Method to execute .
边栏推荐
- Cv2.resize function reports an error: error: (-215:assertion failed) func= 0 in function ‘cv::hal::resize‘
- 【AI4Code】《CodeBERT: A Pre-Trained Model for Programming and Natural Languages》 EMNLP 2020
- Moving Chinese figure liushenglan
- 机器学习强基计划0-4:通俗理解奥卡姆剃刀与没有免费午餐定理
- 【AI4Code】《GraphCodeBERT: Pre-Training Code Representations With DataFlow》 ICLR 2021
- 【CSDN 年终总结】结束与开始,一直在路上—— “1+1=王”的2021总结
- "Autobiography of Franklin" cultivation
- Eccv2022 | transclassp class level grab posture migration
- Machine learning strong foundation program 0-4: popular understanding of Occam razor and no free lunch theorem
- 【问题解决】org.apache.ibatis.exceptions.PersistenceException: Error building SqlSession.1 字节的 UTF-8 序列的字
猜你喜欢

Clickhouse notes 03-- grafana accesses Clickhouse

Connotation and application of industrial Internet

Mid 2022 review | latest progress of large model technology Lanzhou Technology

Convolutional neural network model -- vgg-16 network structure and code implementation

【AI4Code】《Unified Pre-training for Program Understanding and Generation》 NAACL 2021
详解浮点数的精度问题

【OpenCV 例程 300篇】239. Harris 角点检测之精确定位(cornerSubPix)

ESP32-C3 基于Arduino框架下Blinker点灯控制10路开关或继电器组

Microsoft proposed CodeT: a new SOTA for code generation, with 20 points of performance improvement

Word style and multi-level list setting skills (II)
随机推荐
零基础学习CANoe Panel(16)—— Clock Control/Panel Control/Start Stop Control/Tab Control
如何用因果推断和实验驱动用户增长? | 7月28日TF67
牛客论坛项目部署总结
web安全入门-UDP测试与防御
机器学习强基计划0-4:通俗理解奥卡姆剃刀与没有免费午餐定理
【AI4Code】《CodeBERT: A Pre-Trained Model for Programming and Natural Languages》 EMNLP 2020
跌荡的人生
业务可视化-让你的流程图'Run'起来(3.分支选择&跨语言分布式运行节点)
卷积神经网络模型之——LeNet网络结构与代码实现
ORAN专题系列-21:主要的玩家(设备商)以及他们各自的态度、擅长领域
Business visualization - make your flowchart'run'(3. Branch selection & cross language distributed operation node)
卷积核越大性能越强?一文解读RepLKNet模型
卷积神经网络模型之——AlexNet网络结构与代码实现
Date and time function of MySQL function summary
conda常用命令:安装,更新,创建,激活,关闭,查看,卸载,删除,清理,重命名,换源,问题
【视频】马尔可夫链原理可视化解释与R语言区制转换MRS实例|数据分享
CONDA common commands: install, update, create, activate, close, view, uninstall, delete, clean, rename, change source, problem
Azure Devops(十四) 使用Azure的私有Nuget仓库
Zero basic learning canoe panel (15) -- CAPL output view
Shell common script: judge whether the file of the remote host exists