springboot多线程安全demo

下面例子是线程安不安全实例

复制代码
import com.vip.vman.client.zk.ZkLock;
import com.vip.vman.result.BasicResult;
import com.vip.vman.service.job.ZKJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping(value = "/vman/sys2")
public class System2Controller {

    @Autowired
    ZKJob zkJob;
    private volatile  Integer value = 0;

    //这个是线程不安全的,即使变量设置了volatile
    @RequestMapping(value = "/cacheClean3", method = RequestMethod.GET)
    public  BasicResult expireRedis3(){
        BasicResult<Integer> basicResult = new BasicResult<>();
        value++;
        basicResult.setSingleResult(value);
        return basicResult;
    }

    //因为加了synchronized,所以线程安全。这个只能针对单实例安全,但是多实例并也不安全
    @RequestMapping(value = "/cacheClean4", method = RequestMethod.GET)
    public synchronized BasicResult expireRedis4(){
        BasicResult<Integer> basicResult = new BasicResult<>();
        //证
        value++;
        basicResult.setSingleResult(value);
        return basicResult;
    }

    @RequestMapping(value = "/cacheClean5", method = RequestMethod.GET)
    public  BasicResult expireRedis5() throws Exception {
        BasicResult<Integer> basicResult = new BasicResult<>();
        ZkLock lock = new ZkLock(zkJob.getZK(), "/vman/analyse_task_delete/lock2");
        try {
            if( lock.acquire(20, TimeUnit.SECONDS) ) {
                value++;
            }
        }catch (Exception e) {
            log.info("exception:{}",e);
        }finally {
            lock.release();
        }
        basicResult.setSingleResult(value);
        return basicResult;
    }
}
相关推荐
Resean02231 小时前
架构设计系列(十六):DDD 与代码架构
java·开发语言·架构
学长毕设2 小时前
基于SpringBoot 车辆租赁系统平台-附源码
java·spring boot·后端
Flynt4 小时前
Spring AI Alibaba 真停更了?我把它的 GitHub 翻了个底朝天
java·spring·开源
小乖写代码6 小时前
语音通话安全架构 · Voice Call Security Architecture
安全·安全架构·whatsapp·通信安全·语音通话
夜郎king6 小时前
Shapefile 一键生成 GeoServer 样式:GeoTools + Spring Boot 实现 YSLD 自动生成器
spring boot·gis·geotools·ysld
她的男孩7 小时前
Spring Boot 接 Flowable:请假单要同时走财务和行政,包容分支和默认分支怎么配
java·spring boot·工作流引擎
kingx38 小时前
DASCTF空白格:ZIP内空白字符二进制隐写解码
安全·misc·空白字符隐写·zip分析·python解码
咖啡八杯8 小时前
LoginUser 适配器模式:适配 SysUser 到 UserDetails
java·开发语言·后端·框架·适配器模式·若依
北冥有鱼9 小时前
从 bean::method 里抠出注解:Java 方法引用元数据反查全记录
java·后端
上海曼博生物医药科技有限公司9 小时前
人原代肝细胞为什么需要P2备案?从生物安全条件到使用记录
安全·人原料代肝细胞·p2实验室·实验室备案·细胞进口安全管理