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));
    }

原子操作就是,A线程操作了变量,其余所有变量也跟着变化了。请参考我的文章