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

相关文章

Java实现检查多个时间段是否有重合

《Java实现检查多个时间段是否有重合》这篇文章主要为大家详细介绍了如何使用Java实现检查多个时间段是否有重合,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录流程概述步骤详解China编程步骤1:定义时间段类步骤2:添加时间段步骤3:检查时间段是否有重合步骤4:输出结果示例代码结语作

Java中String字符串使用避坑指南

《Java中String字符串使用避坑指南》Java中的String字符串是我们日常编程中用得最多的类之一,看似简单的String使用,却隐藏着不少“坑”,如果不注意,可能会导致性能问题、意外的错误容... 目录8个避坑点如下:1. 字符串的不可变性:每次修改都创建新对象2. 使用 == 比较字符串,陷阱满

Java判断多个时间段是否重合的方法小结

《Java判断多个时间段是否重合的方法小结》这篇文章主要为大家详细介绍了Java中判断多个时间段是否重合的方法,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录判断多个时间段是否有间隔判断时间段集合是否与某时间段重合判断多个时间段是否有间隔实体类内容public class D

IDEA编译报错“java: 常量字符串过长”的原因及解决方法

《IDEA编译报错“java:常量字符串过长”的原因及解决方法》今天在开发过程中,由于尝试将一个文件的Base64字符串设置为常量,结果导致IDEA编译的时候出现了如下报错java:常量字符串过长,... 目录一、问题描述二、问题原因2.1 理论角度2.2 源码角度三、解决方案解决方案①:StringBui

Java覆盖第三方jar包中的某一个类的实现方法

《Java覆盖第三方jar包中的某一个类的实现方法》在我们日常的开发中,经常需要使用第三方的jar包,有时候我们会发现第三方的jar包中的某一个类有问题,或者我们需要定制化修改其中的逻辑,那么应该如何... 目录一、需求描述二、示例描述三、操作步骤四、验证结果五、实现原理一、需求描述需求描述如下:需要在

Java中ArrayList和LinkedList有什么区别举例详解

《Java中ArrayList和LinkedList有什么区别举例详解》:本文主要介绍Java中ArrayList和LinkedList区别的相关资料,包括数据结构特性、核心操作性能、内存与GC影... 目录一、底层数据结构二、核心操作性能对比三、内存与 GC 影响四、扩容机制五、线程安全与并发方案六、工程

JavaScript中的reduce方法执行过程、使用场景及进阶用法

《JavaScript中的reduce方法执行过程、使用场景及进阶用法》:本文主要介绍JavaScript中的reduce方法执行过程、使用场景及进阶用法的相关资料,reduce是JavaScri... 目录1. 什么是reduce2. reduce语法2.1 语法2.2 参数说明3. reduce执行过程

如何使用Java实现请求deepseek

《如何使用Java实现请求deepseek》这篇文章主要为大家详细介绍了如何使用Java实现请求deepseek功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1.deepseek的api创建2.Java实现请求deepseek2.1 pom文件2.2 json转化文件2.2

Java调用DeepSeek API的最佳实践及详细代码示例

《Java调用DeepSeekAPI的最佳实践及详细代码示例》:本文主要介绍如何使用Java调用DeepSeekAPI,包括获取API密钥、添加HTTP客户端依赖、创建HTTP请求、处理响应、... 目录1. 获取API密钥2. 添加HTTP客户端依赖3. 创建HTTP请求4. 处理响应5. 错误处理6.

Spring AI集成DeepSeek的详细步骤

《SpringAI集成DeepSeek的详细步骤》DeepSeek作为一款卓越的国产AI模型,越来越多的公司考虑在自己的应用中集成,对于Java应用来说,我们可以借助SpringAI集成DeepSe... 目录DeepSeek 介绍Spring AI 是什么?1、环境准备2、构建项目2.1、pom依赖2.2