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学习手册之Filter和Listener使用方法

《Java学习手册之Filter和Listener使用方法》:本文主要介绍Java学习手册之Filter和Listener使用方法的相关资料,Filter是一种拦截器,可以在请求到达Servl... 目录一、Filter(过滤器)1. Filter 的工作原理2. Filter 的配置与使用二、Listen

Spring Boot中JSON数值溢出问题从报错到优雅解决办法

《SpringBoot中JSON数值溢出问题从报错到优雅解决办法》:本文主要介绍SpringBoot中JSON数值溢出问题从报错到优雅的解决办法,通过修改字段类型为Long、添加全局异常处理和... 目录一、问题背景:为什么我的接口突然报错了?二、为什么会发生这个错误?1. Java 数据类型的“容量”限制

Java对象转换的实现方式汇总

《Java对象转换的实现方式汇总》:本文主要介绍Java对象转换的多种实现方式,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录Java对象转换的多种实现方式1. 手动映射(Manual Mapping)2. Builder模式3. 工具类辅助映

SpringBoot请求参数接收控制指南分享

《SpringBoot请求参数接收控制指南分享》:本文主要介绍SpringBoot请求参数接收控制指南,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录Spring Boot 请求参数接收控制指南1. 概述2. 有注解时参数接收方式对比3. 无注解时接收参数默认位置

SpringBoot基于配置实现短信服务策略的动态切换

《SpringBoot基于配置实现短信服务策略的动态切换》这篇文章主要为大家详细介绍了SpringBoot在接入多个短信服务商(如阿里云、腾讯云、华为云)后,如何根据配置或环境切换使用不同的服务商,需... 目录目标功能示例配置(application.yml)配置类绑定短信发送策略接口示例:阿里云 & 腾

SpringBoot项目中报错The field screenShot exceeds its maximum permitted size of 1048576 bytes.的问题及解决

《SpringBoot项目中报错ThefieldscreenShotexceedsitsmaximumpermittedsizeof1048576bytes.的问题及解决》这篇文章... 目录项目场景问题描述原因分析解决方案总结项目场景javascript提示:项目相关背景:项目场景:基于Spring

Spring Boot 整合 SSE的高级实践(Server-Sent Events)

《SpringBoot整合SSE的高级实践(Server-SentEvents)》SSE(Server-SentEvents)是一种基于HTTP协议的单向通信机制,允许服务器向浏览器持续发送实... 目录1、简述2、Spring Boot 中的SSE实现2.1 添加依赖2.2 实现后端接口2.3 配置超时时

Spring Boot读取配置文件的五种方式小结

《SpringBoot读取配置文件的五种方式小结》SpringBoot提供了灵活多样的方式来读取配置文件,这篇文章为大家介绍了5种常见的读取方式,文中的示例代码简洁易懂,大家可以根据自己的需要进... 目录1. 配置文件位置与加载顺序2. 读取配置文件的方式汇总方式一:使用 @Value 注解读取配置方式二

一文详解Java异常处理你都了解哪些知识

《一文详解Java异常处理你都了解哪些知识》:本文主要介绍Java异常处理的相关资料,包括异常的分类、捕获和处理异常的语法、常见的异常类型以及自定义异常的实现,文中通过代码介绍的非常详细,需要的朋... 目录前言一、什么是异常二、异常的分类2.1 受检异常2.2 非受检异常三、异常处理的语法3.1 try-

Java中的@SneakyThrows注解用法详解

《Java中的@SneakyThrows注解用法详解》:本文主要介绍Java中的@SneakyThrows注解用法的相关资料,Lombok的@SneakyThrows注解简化了Java方法中的异常... 目录前言一、@SneakyThrows 简介1.1 什么是 Lombok?二、@SneakyThrows