!504 修复Opt.ofTry中并发环境下线程安全问题

Merge pull request !504 from 阿超/v5-dev
This commit is contained in:
Looly 2022-01-17 10:07:15 +00:00 committed by Gitee
commit 92afc0b757
No known key found for this signature in database
GPG Key ID: 173E9B9CA92EEF8F
2 changed files with 16 additions and 1 deletions

View File

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

View File

@ -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