生命有所坚持而生存可以随遇而安 2021-11-08 11:05 采纳率: 50%
浏览 18
已结题

java并发访问,如何避免重复插入,何谓原子操作,请ds指点。下面有贴出具体代码。

//数据插入实现类(AssetCrudService.java)

public synchronized int add(Asset asset) {
        int r;
        if ((r = this.checkName(asset)) > 1 || (r = this.checkMac(asset)) > 1) {
            return r;
        }
        logger.debug("add");
        List<Asset> temp = new ArrayList<>(assetCache.size());
        temp.addAll(assetCache);//public volatile List<Asset> assetCache = Collections.synchronizedList(new ArrayList<>());
        assetCache.add(asset);
        if (this.assetDao.add(asset)) {
            return 1;
        }
        assetCache = temp;
        return 3001;
    }

//测试类

@Test
    public void test1() throws InterruptedException {
        CountDownLatch start = new CountDownLatch(1);
        CountDownLatch end = new CountDownLatch(50);
        Asset asset = new Asset("1", "77:45:01:3C:BF:12", 1, 12);//待插入的数据
        for (int i = 0; i < 50; i++) {
            new Thread(() -> {
                try {
                    start.await();
                    int add = assetCrudService.add(asset);
                    logger.debug("线程名称:{}, 返回结果:{}", Thread.currentThread().getName(), add);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    end.countDown();
                }
            }).start();
        }
        start.countDown();
        end.await();
        new Thread(() -> {
            int add = assetCrudService.add(asset);
            logger.debug("线程名称:{}, 返回结果11:{}", Thread.currentThread().getName(), add);
        }).start();
        logger.debug("assetCache:{}", JsonTools.writeValueAsString(this.assetCrudService.assetCache, true));
    }

  • 写回答

1条回答 默认 最新

报告相同问题?

问题事件

  • 系统已结题 11月16日
  • 已采纳回答 11月8日
  • 创建了问题 11月8日

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失