//数据插入实现类(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));
}