Java并发 - 线程安全类探索(1)

2024-01-11 17:52

本文主要是介绍Java并发 - 线程安全类探索(1),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1.简单设置线程安全类

设计车辆追踪器,获取车辆位置和更新车辆位置信息(坐标x,y)展示显示化大屏

版本一

  • 非线程安全车辆对象【不可变】(MutablePoint)
  • 线程安全车辆容器
// 非线程安全
public class MutablePoint {public int x, y;public MutablePoint() {this.x = 0;this.y = 0;}public MutablePoint(MutablePoint point) {this.x = point.x;this.y = point.y;}
}
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;public class MonitorVehicleTracker {private final Map<String, MutablePoint> locations;public MonitorVehicleTracker(Map<String, MutablePoint> locations) {this.locations = deepCopy(locations);}public synchronized Map<String,MutablePoint> getLocations(){return deepCopy(locations);}// 获取当前车的坐标public synchronized MutablePoint getLocations(String id) {MutablePoint mutablePoint = locations.get(id);return mutablePoint == null ? null : new MutablePoint(mutablePoint);}// 更新车辆的位置public synchronized void setLocations(String id, int x, int y) {MutablePoint mutablePoint = locations.get(id);if (null == mutablePoint) {throw new IllegalArgumentException("No such ID :" + id);}mutablePoint.x = x;mutablePoint.y = y;}// 深度复制private static Map<String, MutablePoint> deepCopy(Map<String, MutablePoint> m) {Map<String, MutablePoint> result = new HashMap<>();for (String id : m.keySet()) {result.put(id, new MutablePoint(m.get(id)));}// 创建一个不可变,不可修改的Mapreturn Collections.unmodifiableMap(result);}
}

版本优缺点

  • 优点
    • getLocations可保证数据一致性
  • 缺点
    • 使用deepCopy方式保证线程安全,对象的大量创建会导致内存不足
    • getLocations时获取的车辆信息不是最新车辆信息

getLocations分析:

在getLocations和setLocations使用sync同步字段,在导出数据时,若locations对象数据很大,此时其他线程调用了setLocations时便会阻塞住,则当前线程导出的数据与用户查看的数据一致(数据一致性)。但数据没有发生更新。

版本二

  • 线程安全车辆对象【不可变】(Point)
  • 线程安全车辆容器(DelegatingVehicleTracker)
// 使用了final作用域,对象状态线程安全,“不可变性”
public class Point {public final int x,y;public Point(int x, int y) {this.x = x;this.y = y;}
}
//使用线程安全容器concurrentHashMap保证线程安全
public class DelegatingVehicleTracker {// 另外一种线程安全的方式CopyOnWriteArrayListprivate final ConcurrentMap<String, Point> locations;private final Map<String, Point> unmodiflableMap;public DelegatingVehicleTracker(Map<String, Point> points) {locations = new ConcurrentHashMap<>(points);unmodiflableMap = Collections.unmodifiableMap(locations);}// 返回的车辆信息拥有当前线程的数据一致性。线程A导出,线程B更新车辆位置的时候,线程A导出的数据还是他之前获取的数据。public Map<String,Point> getLocationsNotChange(){return Collections.unmodifiableMap(new HashMap<>(locations));}// 获取的数据是及时发生更改的,返回的是车辆的快照public Map<String, Point> getLocations() {return locations;}public Point getLocations(String id) {return locations.get(id);}public void setLocations(String id, int x, int y) {// 替换key中的值if (locations.replace(id, new Point(x, y)) == null) {throw new IllegalArgumentException("invalid vehicle name:" + id);}}
}

仔细观察上述版本一和版本二中getLocations及保存车辆的容器,容器如何保证线程安全,及getLocations如何保证数据一致性与保证获取的是最新数据。

版本三

  • 线程安全车辆对象【可变】(SafePoint )
  • 线程安全车辆容器(PublishingVehicleTracker )
public class SafePoint {private int x, y;public SafePoint(int[] a) {this(a[0], a[1]);}public SafePoint(SafePoint p) {this.x = p.x;this.y = p.y;}// 使用对象锁public synchronized int[] get() {return new int[]{x, y};}public SafePoint(int x, int y) {this.x = x;this.y = y;}// 使用对象锁public synchronized void set(int x, int y) {this.x = x;this.y = y;}
}
// 可发布
public class PublishingVehicleTracker {private final Map<String, SafePoint> locations;private final Map<String, SafePoint> umodifiableMap;// TODO 把线程安全委托给ConcurrentHashMappublic PublishingVehicleTracker(Map<String, SafePoint> locations) {this.locations = new ConcurrentHashMap<>(locations);this.umodifiableMap = Collections.unmodifiableMap(this.locations);}public Map<String, SafePoint> getLocations() {return this.umodifiableMap;}public SafePoint getLocations(String id) {return locations.get(id);}public void setLocations(String id, int x, int y) {if (!locations.containsKey(id)) {throw new IllegalArgumentException("invalid vehicle name :" + id);}// TODO locations.get 和 set 都是竞争同一个锁的。这样子才能保证线程安全。如果x,y 分别设置一个set和get则导致x和y中出现修改了x,而y还没有更改locations.get(id).set(x, y);	}
}

观察上述版本二和版本三中如何保证车辆信息对象在可变条件下线程安全。

2.对现在有的线程安全类添加功能小探索。

  • 代码复用
  • 开发成本及维护成本(原有的代码已经测试过)

假设需要一个线程安全链表,他提供一个原子的“若没有则添加(Put-If-Absent)” 同步的List已实现了大部分功能,我们可以根据他提供的contains和add方法来构造一个“若没有则添加”的操作。

实现”若没有则添加“的概念很简单:先检查再执行。先检查这个元素是否存在,不存在则进行添加

  1. 修改原始类(通常无法做到)

  2. 扩展类(并非所有类的状态都向子类公开,大部分不适合)

    public class BetterVector<E> extends Vector<E>{public synchronized boolean putIfAbsent(E x){boolean absent = !contains(x);if(absent)add(x);return absent;}
    }
    
  3. 客户端加锁(非线程安全)

    public class ListHelper<E>{public List<E> list = Collections.synchronized(new ArrayList<E>());// 无效加锁 ListHelper锁假象。list 跟 ListHelper 是两个对象public synchronized boolean putIfAbsent(E x){boolean absent = !list.contains(x);if(absent)add(x);return absent;}
    }
    
  4. 客户端加锁(线程安全)

    public class ListHelper<E>{public List<E> list = Collections.synchronized(new ArrayList<E>());public boolean putIfAbsent(E x){synchronized(list){boolean absent = !list.contains(x);if(absent)add(x);return absent;}}
    }
    
  5. 组合(用户只能通过ImprovedList 访问)

    public class ImprovedList<T> implements List<T> {private final List<T> list;public ImprovedList(List<T> list){this.list = list;}public synchronized boolean putIfAbsent(T x) {boolean absent = !list.contains(x);if(absent)add(x);return absent;}public synchronized void clear(){list.clear();}// ... 按照类似的方式委托List的其他方法
    }
    

这篇关于Java并发 - 线程安全类探索(1)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/595220

相关文章

Spring Boot 实现 IP 限流的原理、实践与利弊解析

《SpringBoot实现IP限流的原理、实践与利弊解析》在SpringBoot中实现IP限流是一种简单而有效的方式来保障系统的稳定性和可用性,本文给大家介绍SpringBoot实现IP限... 目录一、引言二、IP 限流原理2.1 令牌桶算法2.2 漏桶算法三、使用场景3.1 防止恶意攻击3.2 控制资源

Mac系统下卸载JAVA和JDK的步骤

《Mac系统下卸载JAVA和JDK的步骤》JDK是Java语言的软件开发工具包,它提供了开发和运行Java应用程序所需的工具、库和资源,:本文主要介绍Mac系统下卸载JAVA和JDK的相关资料,需... 目录1. 卸载系统自带的 Java 版本检查当前 Java 版本通过命令卸载系统 Java2. 卸载自定

springboot下载接口限速功能实现

《springboot下载接口限速功能实现》通过Redis统计并发数动态调整每个用户带宽,核心逻辑为每秒读取并发送限定数据量,防止单用户占用过多资源,确保整体下载均衡且高效,本文给大家介绍spring... 目录 一、整体目标 二、涉及的主要类/方法✅ 三、核心流程图解(简化) 四、关键代码详解1️⃣ 设置

Java Spring ApplicationEvent 代码示例解析

《JavaSpringApplicationEvent代码示例解析》本文解析了Spring事件机制,涵盖核心概念(发布-订阅/观察者模式)、代码实现(事件定义、发布、监听)及高级应用(异步处理、... 目录一、Spring 事件机制核心概念1. 事件驱动架构模型2. 核心组件二、代码示例解析1. 事件定义

SpringMVC高效获取JavaBean对象指南

《SpringMVC高效获取JavaBean对象指南》SpringMVC通过数据绑定自动将请求参数映射到JavaBean,支持表单、URL及JSON数据,需用@ModelAttribute、@Requ... 目录Spring MVC 获取 JavaBean 对象指南核心机制:数据绑定实现步骤1. 定义 Ja

javax.net.ssl.SSLHandshakeException:异常原因及解决方案

《javax.net.ssl.SSLHandshakeException:异常原因及解决方案》javax.net.ssl.SSLHandshakeException是一个SSL握手异常,通常在建立SS... 目录报错原因在程序中绕过服务器的安全验证注意点最后多说一句报错原因一般出现这种问题是因为目标服务器

Java实现删除文件中的指定内容

《Java实现删除文件中的指定内容》在日常开发中,经常需要对文本文件进行批量处理,其中,删除文件中指定内容是最常见的需求之一,下面我们就来看看如何使用java实现删除文件中的指定内容吧... 目录1. 项目背景详细介绍2. 项目需求详细介绍2.1 功能需求2.2 非功能需求3. 相关技术详细介绍3.1 Ja

springboot项目中整合高德地图的实践

《springboot项目中整合高德地图的实践》:本文主要介绍springboot项目中整合高德地图的实践,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一:高德开放平台的使用二:创建数据库(我是用的是mysql)三:Springboot所需的依赖(根据你的需求再

spring中的ImportSelector接口示例详解

《spring中的ImportSelector接口示例详解》Spring的ImportSelector接口用于动态选择配置类,实现条件化和模块化配置,关键方法selectImports根据注解信息返回... 目录一、核心作用二、关键方法三、扩展功能四、使用示例五、工作原理六、应用场景七、自定义实现Impor

SpringBoot3应用中集成和使用Spring Retry的实践记录

《SpringBoot3应用中集成和使用SpringRetry的实践记录》SpringRetry为SpringBoot3提供重试机制,支持注解和编程式两种方式,可配置重试策略与监听器,适用于临时性故... 目录1. 简介2. 环境准备3. 使用方式3.1 注解方式 基础使用自定义重试策略失败恢复机制注意事项