Skip to content

Commit

Permalink
SimpleFuture增加异常捕获
Browse files Browse the repository at this point in the history
  • Loading branch information
leaderli committed Oct 17, 2024
1 parent 92d9eca commit afdcc83
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -128,13 +128,18 @@ public void submit(Callable<T> supplier) {


public void submit(ExecutorService executorService, Callable<T> supplier) {
executorService.submit(() -> {
try {
setResult(supplier.call());
} catch (Exception e) {
setException(e);
}
});
try {

executorService.submit(() -> {
try {
setResult(supplier.call());
} catch (Exception e) {
setException(e);
}
});
} catch (RejectedExecutionException e) {
submit(supplier);
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

Expand All @@ -14,7 +16,7 @@
class SimpleFutureTest {

@Test
void test() throws InterruptedException {
void test() throws InterruptedException, TimeoutException {
SimpleFuture<Integer> simpleFuture = new SimpleFuture<>();
simpleFuture.submit(() -> ThreadUtil.delay(30, () -> 1));
Assertions.assertThrows(TimeoutException.class, () -> simpleFuture.get(10, TimeUnit.MILLISECONDS));
Expand All @@ -37,6 +39,11 @@ void test() throws InterruptedException {
Assertions.assertNull(simpleFuture3.get());
Assertions.assertEquals(RuntimeException.class, simpleFuture3.getException().getClass());

ExecutorService executorService = Executors.newFixedThreadPool(1);
SimpleFuture<Integer> simpleFuture4 = new SimpleFuture<>();
simpleFuture4.submit(executorService, () -> 1);
Assertions.assertEquals(1, simpleFuture4.get());


}

Expand Down

0 comments on commit afdcc83

Please sign in to comment.