在线求CR,你觉得我这段Java代码还有优化的空间吗?


@Service
public class AssetServiceImpl implements AssetService {
@Autowired
private TransactionTemplate transactionTemplate;
@Override
public String update(Asset asset) {
//参数检查、幂等校验、从数据库取出最新asset等。
return transactionTemplate.execute(status -> {
updateAsset(asset);
return insertAssetStream(asset);
});
}
}
public class AssetServiceImplTest {
private static ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
.setNameFormat("demo-pool-%d").build();
private static ExecutorService pool = new ThreadPoolExecutor(20, 100,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(128), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());
@Autowired
private AssetService assetService;
@Test
public void test_updateConcurrent() {
Asset asset = getAsset();
//参数的准备
//...
//并发场景模拟
CountDownLatch countDownLatch = new CountDownLatch(10);
AtomicInteger atomicInteger =new AtomicInteger();
//并发批量修改,只有一条可以修改成功
for (int i = 0; i < 10; i++) {
pool.execute(() -> {
try {
String streamNo = assetService.update(asset);
} catch (Exception e) {
System.out.println("Error : " + e);
failedCount.getAndIncrement();
} finally {
countDownLatch.countDown();
}
});
}
try {
//主线程等子线程都执行完之后查询最新的资产
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
Assert.assertEquals(failedCount.intValue(), 9);
// 从数据库中反查出最新的Asset
// 再对关键字段做注意校验
}
}
线程池
try {
String streamNo = assetService.update(asset);
} catch (Exception e) {
System.out.println("Error : " + e);
failedCount.increment();
} finally {
countDownLatch.countDown();
}
这里就可以用到CyclicBarrier来实现,CyclicBarrier和CountDownLatch一样,都是关于线程的计数器。
//主线程根据此CountDownLatch阻塞
CountDownLatch mainThreadHolder = new CountDownLatch(10);
//并发的多个子线程根据此CyclicBarrier阻塞
CyclicBarrier cyclicBarrier = new CyclicBarrier(10);
//失败次数计数器
LongAdder failedCount = new LongAdder();
//并发批量修改,只有一条可以修改成功
for (int i = 0; i < 10; i++) {
pool.execute(() -> {
try {
//子线程等待,所有线程就绪后开始执行
cyclicBarrier.await();
//调用被测试的方法
String streamNo = assetService.update(asset);
} catch (Exception e) {
//异常发生时,对失败计数器+1
System.out.println("Error : " + e);
failedCount.increment();
} finally {
//主线程的阻塞器奇数-1
mainThreadHolder.countDown();
}
});
}
try {
//主线程等子线程都执行完之后查询最新的资产池计划
mainThreadHolder.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
//断言,保证失败9次,则成功一次
Assert.assertEquals(failedCount.intValue(), 9);
// 从数据库中反查出最新的Asset
// 再对关键字段做注意校验
欢迎关注微信公众号:互联网全栈架构,收取更多有价值的信息。