当前位置:网站首页>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 .
边栏推荐
- Docker学习 - Redis集群-3主3从-扩容-缩容搭建
- 全球都热炸了,谷歌服务器已经崩掉了
- 微软提出CodeT:代码生成新SOTA,20个点的性能提升
- 【问题解决】ibatis.binding.BindingException: Type interface xxDao is not known to the MapperRegistry.
- Zero basic learning canoe panel (14) -- led control and LCD control
- 【GCN】《Adaptive Propagation Graph Convolutional Network》(TNNLS 2020)
- Clickhouse notes 03-- grafana accesses Clickhouse
- clickhouse笔记03-- Grafana 接入ClickHouse
- 一味地做大元宇宙的规模,已经背离了元宇宙本该有的发展逻辑
- yum和vim须掌握的常用操作
猜你喜欢

cv2.resize函数报错:error: (-215:Assertion failed) func != 0 in function ‘cv::hal::resize‘

【CSDN 年终总结】结束与开始,一直在路上—— “1+1=王”的2021总结
![[problem solving] org.apache.ibatis.exceptions PersistenceException: Error building SqlSession. 1-byte word of UTF-8 sequence](/img/fd/245306273e464c04f3292132fbfa2f.png)
[problem solving] org.apache.ibatis.exceptions PersistenceException: Error building SqlSession. 1-byte word of UTF-8 sequence

【AI4Code】《CoSQA: 20,000+ Web Queries for Code Search and Question Answering》 ACL 2021

B树和B+树

G027-OP-INS-RHEL-04 RedHat OpenStack 创建自定义的QCOW2格式镜像

OAuth,JWT ,OIDC你们搞得我好乱啊

【OpenCV 例程 300篇】239. Harris 角点检测之精确定位(cornerSubPix)
详解浮点数的精度问题

2022.07.24 (lc_6125_equal row and column pairs)
随机推荐
cv2.resize函数报错:error: (-215:Assertion failed) func != 0 in function ‘cv::hal::resize‘
Cv2.resize function reports an error: error: (-215:assertion failed) func= 0 in function ‘cv::hal::resize‘
深度学习的训练、预测过程详解【以LeNet模型和CIFAR10数据集为例】
Migrate PaloAlto ha high availability firewall to panorama
Simple understanding of flow
JS sorts according to the attributes of the elements in the array
2022 年中回顾 | 大模型技术最新进展 澜舟科技
简单了解流
"Wei Lai Cup" 2022 Niuke summer multi school training camp 2 supplementary problem solution (g, J, K, l)
Zero basic learning canoe panel (15) -- CAPL output view
详解浮点数的精度问题
【问题解决】ibatis.binding.BindingException: Type interface xxDao is not known to the MapperRegistry.
Chapter5 : Deep Learning and Computational Chemistry
机器学习强基计划0-4:通俗理解奥卡姆剃刀与没有免费午餐定理
CONDA common commands: install, update, create, activate, close, view, uninstall, delete, clean, rename, change source, problem
全球都热炸了,谷歌服务器已经崩掉了
Date and time function of MySQL function summary
程序的内存布局
Django 2 ----- 数据库与Admin
Mysql 远程连接权限错误1045问题