mirror of
https://gitee.com/dromara/hutool.git
synced 2025-04-05 17:37:59 +08:00
修复ofTry中并发环境下线程安全问题
This commit is contained in:
parent
78ac9fcdef
commit
cba1659833
@ -122,7 +122,7 @@ public class Opt<T> {
|
||||
try {
|
||||
return Opt.ofNullable(supplier.call());
|
||||
} catch (Exception e) {
|
||||
final Opt<T> empty = Opt.empty();
|
||||
final Opt<T> empty = new Opt<>(null);
|
||||
empty.exception = e;
|
||||
return empty;
|
||||
}
|
||||
|
@ -187,6 +187,21 @@ public class OptTest {
|
||||
Assert.assertEquals(indexOut, indexOutSituation);
|
||||
Assert.assertEquals("hutool", npe);
|
||||
Assert.assertEquals("hutool", indexOut);
|
||||
|
||||
// 多线程下情况测试
|
||||
Stream.iterate(0, i -> ++i).limit(20000).parallel().forEach(i -> {
|
||||
Opt<Object> opt = Opt.ofTry(() -> {
|
||||
if (i % 2 == 0) {
|
||||
throw new IllegalStateException(i + "");
|
||||
} else {
|
||||
throw new NullPointerException(i + "");
|
||||
}
|
||||
});
|
||||
Assert.assertTrue(
|
||||
(i % 2 == 0 && opt.getException() instanceof IllegalStateException) ||
|
||||
(i % 2 != 0 && opt.getException() instanceof NullPointerException)
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
@Data
|
||||
|
Loading…
Reference in New Issue
Block a user