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

相关文章

JVM 的类初始化机制

前言 当你在 Java 程序中new对象时,有没有考虑过 JVM 是如何把静态的字节码(byte code)转化为运行时对象的呢,这个问题看似简单,但清楚的同学相信也不会太多,这篇文章首先介绍 JVM 类初始化的机制,然后给出几个易出错的实例来分析,帮助大家更好理解这个知识点。 JVM 将字节码转化为运行时对象分为三个阶段,分别是:loading 、Linking、initialization

Spring Security 基于表达式的权限控制

前言 spring security 3.0已经可以使用spring el表达式来控制授权,允许在表达式中使用复杂的布尔逻辑来控制访问的权限。 常见的表达式 Spring Security可用表达式对象的基类是SecurityExpressionRoot。 表达式描述hasRole([role])用户拥有制定的角色时返回true (Spring security默认会带有ROLE_前缀),去

浅析Spring Security认证过程

类图 为了方便理解Spring Security认证流程,特意画了如下的类图,包含相关的核心认证类 概述 核心验证器 AuthenticationManager 该对象提供了认证方法的入口,接收一个Authentiaton对象作为参数; public interface AuthenticationManager {Authentication authenticate(Authenti

Spring Security--Architecture Overview

1 核心组件 这一节主要介绍一些在Spring Security中常见且核心的Java类,它们之间的依赖,构建起了整个框架。想要理解整个架构,最起码得对这些类眼熟。 1.1 SecurityContextHolder SecurityContextHolder用于存储安全上下文(security context)的信息。当前操作的用户是谁,该用户是否已经被认证,他拥有哪些角色权限…这些都被保

Spring Security基于数据库验证流程详解

Spring Security 校验流程图 相关解释说明(认真看哦) AbstractAuthenticationProcessingFilter 抽象类 /*** 调用 #requiresAuthentication(HttpServletRequest, HttpServletResponse) 决定是否需要进行验证操作。* 如果需要验证,则会调用 #attemptAuthentica

Spring Security 从入门到进阶系列教程

Spring Security 入门系列 《保护 Web 应用的安全》 《Spring-Security-入门(一):登录与退出》 《Spring-Security-入门(二):基于数据库验证》 《Spring-Security-入门(三):密码加密》 《Spring-Security-入门(四):自定义-Filter》 《Spring-Security-入门(五):在 Sprin

Java架构师知识体认识

源码分析 常用设计模式 Proxy代理模式Factory工厂模式Singleton单例模式Delegate委派模式Strategy策略模式Prototype原型模式Template模板模式 Spring5 beans 接口实例化代理Bean操作 Context Ioc容器设计原理及高级特性Aop设计原理Factorybean与Beanfactory Transaction 声明式事物

Java进阶13讲__第12讲_1/2

多线程、线程池 1.  线程概念 1.1  什么是线程 1.2  线程的好处 2.   创建线程的三种方式 注意事项 2.1  继承Thread类 2.1.1 认识  2.1.2  编码实现  package cn.hdc.oop10.Thread;import org.slf4j.Logger;import org.slf4j.LoggerFactory

深入探索协同过滤:从原理到推荐模块案例

文章目录 前言一、协同过滤1. 基于用户的协同过滤(UserCF)2. 基于物品的协同过滤(ItemCF)3. 相似度计算方法 二、相似度计算方法1. 欧氏距离2. 皮尔逊相关系数3. 杰卡德相似系数4. 余弦相似度 三、推荐模块案例1.基于文章的协同过滤推荐功能2.基于用户的协同过滤推荐功能 前言     在信息过载的时代,推荐系统成为连接用户与内容的桥梁。本文聚焦于

JAVA智听未来一站式有声阅读平台听书系统小程序源码

智听未来,一站式有声阅读平台听书系统 🌟&nbsp;开篇:遇见未来,从“智听”开始 在这个快节奏的时代,你是否渴望在忙碌的间隙,找到一片属于自己的宁静角落?是否梦想着能随时随地,沉浸在知识的海洋,或是故事的奇幻世界里?今天,就让我带你一起探索“智听未来”——这一站式有声阅读平台听书系统,它正悄悄改变着我们的阅读方式,让未来触手可及! 📚&nbsp;第一站:海量资源,应有尽有 走进“智听