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集成Druid实现数据源管理与监控的详细步骤

《SpringBoot集成Druid实现数据源管理与监控的详细步骤》本文介绍如何在SpringBoot项目中集成Druid数据库连接池,包括环境搭建、Maven依赖配置、SpringBoot配置文件... 目录1. 引言1.1 环境准备1.2 Druid介绍2. 配置Druid连接池3. 查看Druid监控

Java中读取YAML文件配置信息常见问题及解决方法

《Java中读取YAML文件配置信息常见问题及解决方法》:本文主要介绍Java中读取YAML文件配置信息常见问题及解决方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要... 目录1 使用Spring Boot的@ConfigurationProperties2. 使用@Valu

创建Java keystore文件的完整指南及详细步骤

《创建Javakeystore文件的完整指南及详细步骤》本文详解Java中keystore的创建与配置,涵盖私钥管理、自签名与CA证书生成、SSL/TLS应用,强调安全存储及验证机制,确保通信加密和... 目录1. 秘密键(私钥)的理解与管理私钥的定义与重要性私钥的管理策略私钥的生成与存储2. 证书的创建与

浅析Spring如何控制Bean的加载顺序

《浅析Spring如何控制Bean的加载顺序》在大多数情况下,我们不需要手动控制Bean的加载顺序,因为Spring的IoC容器足够智能,但在某些特殊场景下,这种隐式的依赖关系可能不存在,下面我们就来... 目录核心原则:依赖驱动加载手动控制 Bean 加载顺序的方法方法 1:使用@DependsOn(最直

SpringBoot中如何使用Assert进行断言校验

《SpringBoot中如何使用Assert进行断言校验》Java提供了内置的assert机制,而Spring框架也提供了更强大的Assert工具类来帮助开发者进行参数校验和状态检查,下... 目录前言一、Java 原生assert简介1.1 使用方式1.2 示例代码1.3 优缺点分析二、Spring Fr

java使用protobuf-maven-plugin的插件编译proto文件详解

《java使用protobuf-maven-plugin的插件编译proto文件详解》:本文主要介绍java使用protobuf-maven-plugin的插件编译proto文件,具有很好的参考价... 目录protobuf文件作为数据传输和存储的协议主要介绍在Java使用maven编译proto文件的插件

Java中的数组与集合基本用法详解

《Java中的数组与集合基本用法详解》本文介绍了Java数组和集合框架的基础知识,数组部分涵盖了一维、二维及多维数组的声明、初始化、访问与遍历方法,以及Arrays类的常用操作,对Java数组与集合相... 目录一、Java数组基础1.1 数组结构概述1.2 一维数组1.2.1 声明与初始化1.2.2 访问

Javaee多线程之进程和线程之间的区别和联系(最新整理)

《Javaee多线程之进程和线程之间的区别和联系(最新整理)》进程是资源分配单位,线程是调度执行单位,共享资源更高效,创建线程五种方式:继承Thread、Runnable接口、匿名类、lambda,r... 目录进程和线程进程线程进程和线程的区别创建线程的五种写法继承Thread,重写run实现Runnab

Java 方法重载Overload常见误区及注意事项

《Java方法重载Overload常见误区及注意事项》Java方法重载允许同一类中同名方法通过参数类型、数量、顺序差异实现功能扩展,提升代码灵活性,核心条件为参数列表不同,不涉及返回类型、访问修饰符... 目录Java 方法重载(Overload)详解一、方法重载的核心条件二、构成方法重载的具体情况三、不构

Java通过驱动包(jar包)连接MySQL数据库的步骤总结及验证方式

《Java通过驱动包(jar包)连接MySQL数据库的步骤总结及验证方式》本文详细介绍如何使用Java通过JDBC连接MySQL数据库,包括下载驱动、配置Eclipse环境、检测数据库连接等关键步骤,... 目录一、下载驱动包二、放jar包三、检测数据库连接JavaJava 如何使用 JDBC 连接 mys