Skip to content

Commit 904a740

Browse files
baljeet20pivovarit
authored andcommitted
BAEL-1071 Runnable vs Callable in Java (eugenp#2513)
1 parent 73526dd commit 904a740

2 files changed

Lines changed: 78 additions & 0 deletions

File tree

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package com.baeldung.concurrent.callable;
2+
3+
4+
import java.util.concurrent.Callable;
5+
6+
public class FactorialTask implements Callable<Integer> {
7+
int number;
8+
9+
public FactorialTask(int number) {
10+
this.number = number;
11+
}
12+
13+
public Integer call() throws InvalidParamaterException {
14+
int fact=1;
15+
if(number < 0)
16+
throw new InvalidParamaterException("Number must be positive");
17+
18+
for(int count=number;count>1;count--){
19+
fact=fact * count;
20+
}
21+
22+
return fact;
23+
}
24+
25+
private class InvalidParamaterException extends Exception {
26+
public InvalidParamaterException(String message) {
27+
super(message);
28+
}
29+
}
30+
}
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package com.baeldung.concurrent.callable;
2+
3+
import org.junit.After;
4+
import org.junit.Before;
5+
import org.junit.Test;
6+
7+
import java.util.concurrent.ExecutionException;
8+
import java.util.concurrent.ExecutorService;
9+
import java.util.concurrent.Executors;
10+
import java.util.concurrent.Future;
11+
12+
import static junit.framework.Assert.assertEquals;
13+
14+
public class FactorialTaskManualTest {
15+
16+
private ExecutorService executorService;
17+
18+
@Before
19+
public void setup(){
20+
executorService = Executors.newSingleThreadExecutor();
21+
}
22+
23+
@Test
24+
public void whenTaskSubmitted_ThenFutureResultObtained() throws ExecutionException, InterruptedException {
25+
FactorialTask task = new FactorialTask(5);
26+
Future<Integer> future= executorService.submit(task);
27+
assertEquals(120,future.get().intValue());
28+
}
29+
30+
@Test(expected = ExecutionException.class)
31+
public void whenException_ThenCallableThrowsIt() throws ExecutionException, InterruptedException {
32+
FactorialTask task = new FactorialTask(-5);
33+
Future<Integer> future= executorService.submit(task);
34+
Integer result=future.get().intValue();
35+
}
36+
37+
@Test
38+
public void whenException_ThenCallableDoesntThrowsItIfGetIsNotCalled(){
39+
FactorialTask task = new FactorialTask(-5);
40+
Future<Integer> future= executorService.submit(task);
41+
assertEquals(false,future.isDone());
42+
}
43+
44+
@After
45+
public void cleanup(){
46+
executorService.shutdown();
47+
}
48+
}

0 commit comments

Comments
 (0)