Skip to content

Commit 350b32d

Browse files
author
Rakesh Venkatesh
committed
Refactor code for improved readability and exception handling
1 parent 0e8d17a commit 350b32d

File tree

13 files changed

+88
-91
lines changed

13 files changed

+88
-91
lines changed

multithreading/src/main/java/com/rakeshv/completablefutures/AsyncExample.java

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ public static void main(String[] args) {
6363
emailFuture,
6464
(users, emails) -> {
6565
System.out.println("User size is " + users.size() + " and email size is " + emails.size());
66-
});
66+
});
6767

6868
start.completeAsync(() -> null, starter);
6969
CompletableFuture<List<User>> users1 = completableFuture.thenComposeAsync(fetchUsers);
@@ -81,13 +81,14 @@ public static void main(String[] args) {
8181
executorService1.shutdown();
8282
starter.shutdown();
8383
} catch (Exception e) {
84-
//TODO: handle exception
84+
e.printStackTrace();
8585
}
8686
}
8787

8888
public static void sleep(long millis) {
8989
try {
9090
Thread.sleep(millis);
91-
} catch (Exception e) {}
91+
} catch (Exception e) {
92+
}
9293
}
9394
}

multithreading/src/main/java/com/rakeshv/completablefutures/BmiCalculator.java

Lines changed: 35 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -11,42 +11,44 @@
1111

1212
public class BmiCalculator {
1313
ExecutorService executorService = Executors.newFixedThreadPool(2);
14+
1415
public static void main(String[] args) throws InterruptedException, ExecutionException {
1516
BmiCalculator bmiCalculator = new BmiCalculator();
1617

17-
Scanner scanner = new Scanner(System.in);
18-
19-
System.out.println("Please enter the weight");
20-
double weight = Double.parseDouble(scanner.nextLine());
21-
System.out.println("Please enter the height");
22-
double height = Double.parseDouble(scanner.nextLine());
23-
CompletableFuture<Double> getHeight = supplyAsync(() -> {
24-
if (height <= 0) {
25-
throw new IllegalArgumentException("Height cant be 0");
26-
}
27-
return height;
28-
},bmiCalculator.executorService).exceptionally(ex -> {
29-
System.out.println("Invalid height entered. so considering height as 1m");
30-
return 1.0;
31-
});
32-
33-
CompletableFuture<Double> getWeight = supplyAsync(() -> {
34-
if (weight <= 0) {
35-
throw new IllegalArgumentException("Weight cant be 0");
36-
}
37-
return weight;
38-
}, bmiCalculator.executorService).exceptionally(ex -> {
39-
System.out.println("Invalid weight entered. so considering weight as 1kg");
40-
return 1.0;
41-
});
42-
43-
System.out.println("Calculating BMI");
44-
TimeUnit.SECONDS.sleep(2);
45-
46-
CompletableFuture<Double> bmiFuture = getHeight
47-
.thenCombineAsync(getWeight, (h, w) -> bmiCalculator.getBmi(w, h));
48-
49-
System.out.println(bmiFuture.get());
18+
try (Scanner scanner = new Scanner(System.in)) {
19+
System.out.println("Please enter the weight");
20+
double weight = Double.parseDouble(scanner.nextLine());
21+
System.out.println("Please enter the height");
22+
double height = Double.parseDouble(scanner.nextLine());
23+
24+
CompletableFuture<Double> getHeight = supplyAsync(() -> {
25+
if (height <= 0) {
26+
throw new IllegalArgumentException("Height cant be 0");
27+
}
28+
return height;
29+
}, bmiCalculator.executorService).exceptionally(ex -> {
30+
System.out.println("Invalid height entered. so considering height as 1m");
31+
return 1.0;
32+
});
33+
34+
CompletableFuture<Double> getWeight = supplyAsync(() -> {
35+
if (weight <= 0) {
36+
throw new IllegalArgumentException("Weight cant be 0");
37+
}
38+
return weight;
39+
}, bmiCalculator.executorService).exceptionally(ex -> {
40+
System.out.println("Invalid weight entered. so considering weight as 1kg");
41+
return 1.0;
42+
});
43+
44+
System.out.println("Calculating BMI");
45+
TimeUnit.SECONDS.sleep(2);
46+
47+
CompletableFuture<Double> bmiFuture = getHeight
48+
.thenCombineAsync(getWeight, (h, w) -> bmiCalculator.getBmi(w, h));
49+
50+
System.out.println(bmiFuture.get());
51+
}
5052
bmiCalculator.executorService.shutdownNow();
5153
}
5254

multithreading/src/main/java/com/rakeshv/completablefutures/CompletableFutureDemo.java

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,12 +11,11 @@ public static void main(String[] args) {
1111

1212
Runnable runnable = () -> {
1313
System.out.println("Executing from thread " +
14-
Thread.currentThread().getName());
14+
Thread.currentThread().getName());
1515
};
1616

17-
CompletableFuture completableFuture =
18-
CompletableFuture.runAsync(runnable, executorService);
19-
17+
CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(runnable, executorService);
18+
2019
System.out.println("From main");
2120
completableFuture.join();
2221

@@ -29,15 +28,17 @@ public static void main(String[] args) {
2928
Supplier<String> delayedSupplier = () -> {
3029
try {
3130
Thread.sleep(3000);
32-
} catch (Exception e) {}
31+
} catch (Exception e) {
32+
}
3333

3434
return "sleep complete";
3535
};
3636

3737
CompletableFuture<String> longFuture = CompletableFuture.supplyAsync(delayedSupplier, executorService);
3838
try {
3939
Thread.sleep(1000);
40-
} catch (Exception e) {}
40+
} catch (Exception e) {
41+
}
4142

4243
System.err.print("He is taking long time to complete");
4344
longFuture.complete("He's dead jim");

multithreading/src/main/java/com/rakeshv/completablefutures/HttpClientExample.java

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
package com.rakeshv.completablefutures;
22

3-
import java.io.IOException;
43
import java.net.URI;
54
import java.net.URISyntaxException;
65
import java.net.http.HttpClient;
@@ -12,7 +11,8 @@
1211
import java.util.stream.Collectors;
1312

1413
public class HttpClientExample {
15-
public static void main(String[] args) throws InterruptedException, ExecutionException, TimeoutException, URISyntaxException {
14+
public static void main(String[] args)
15+
throws InterruptedException, ExecutionException, TimeoutException, URISyntaxException {
1616
ExecutorService service = Executors.newFixedThreadPool(5);
1717

1818
HttpClient client = HttpClient.newBuilder()
@@ -24,8 +24,7 @@ public static void main(String[] args) throws InterruptedException, ExecutionExc
2424
new URI("https://www.google.com"),
2525
new URI("https://www.facebook.com"),
2626
new URI("https://www.netflix.com"),
27-
new URI("https://www.twitter.com")
28-
);
27+
new URI("https://www.twitter.com"));
2928

3029
List<CompletableFuture<String>> result = links.stream()
3130
.map(url -> {

multithreading/src/main/java/com/rakeshv/demo1/Demo1.java

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -25,10 +25,8 @@ public static void main(String[] args) {
2525
try {
2626
System.out.println(result.get());
2727
} catch (InterruptedException e) {
28-
// TODO Auto-generated catch block
2928
e.printStackTrace();
3029
} catch (ExecutionException e) {
31-
// TODO Auto-generated catch block
3230
e.printStackTrace();
3331
}
3432
}
@@ -40,15 +38,12 @@ public static void main(String[] args) {
4038
try {
4139
System.out.println(completableFuture.get());
4240
} catch (InterruptedException e) {
43-
// TODO Auto-generated catch block
4441
e.printStackTrace();
4542
} catch (ExecutionException e) {
46-
// TODO Auto-generated catch block
4743
e.printStackTrace();
4844
}
4945
}
5046

51-
5247
}
5348

5449
class Runner extends Thread {

multithreading/src/main/java/com/rakeshv/demo2/Process.java

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,21 +8,24 @@ public static void main(String[] args) {
88
processor.start();
99

1010
System.out.println("Press enter to stop");
11-
Scanner scanner = new Scanner(System.in);
12-
scanner.nextLine();
11+
try (Scanner scanner = new Scanner(System.in)) {
12+
scanner.nextLine();
13+
}
1314
processor.shutdown();
1415
}
1516
}
1617

1718
class Processor extends Thread {
1819
private volatile boolean running = true;
20+
1921
@Override
2022
public void run() {
2123
while (running) {
2224
System.out.println("From thread " + Thread.currentThread().getName());
2325
try {
2426
Thread.sleep(1000);
25-
} catch (Exception e) {}
27+
} catch (Exception e) {
28+
}
2629
}
2730
}
2831

multithreading/src/main/java/com/rakeshv/demo3/Worker.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
package com.rakeshv.demo3;
22

3-
import java.util.concurrent.CompletableFuture;
43
import java.util.concurrent.ExecutorService;
54
import java.util.concurrent.Executors;
65

@@ -29,7 +28,8 @@ public void run() {
2928

3029
try {
3130
Thread.sleep(3000);
32-
} catch (Exception e) {}
31+
} catch (Exception e) {
32+
}
3333
System.out.println("Ending count is " + count);
3434
}
3535
}

multithreading/src/main/java/com/rakeshv/locks/ConditionsDemo.java

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99

1010
public class ConditionsDemo {
1111
InnerStack stack;
12+
1213
public static void main(String[] args) {
1314
InnerStack stack = new InnerStack();
1415
Producer producer = new Producer(stack);
@@ -26,6 +27,7 @@ static class InnerStack {
2627
private Condition stackFullCondition;
2728
private Condition stackEmptyCondition;
2829
private boolean hasMoreItems;
30+
2931
InnerStack() {
3032
stack = new Stack<Object>();
3133
lock = new ReentrantLock();
@@ -45,7 +47,7 @@ void push(Object o) {
4547
Thread.sleep(1000);
4648
stackEmptyCondition.signal();
4749
} catch (Exception e) {
48-
//TODO: handle exception
50+
e.printStackTrace();
4951
} finally {
5052
lock.unlock();
5153
}
@@ -61,7 +63,7 @@ void pop() {
6163
Thread.sleep(1000);
6264
stackFullCondition.signal();
6365
} catch (Exception e) {
64-
//TODO: handle exception
66+
e.printStackTrace();
6567
} finally {
6668
lock.unlock();
6769
}
@@ -71,7 +73,7 @@ void pop() {
7173
static class Producer {
7274
private InnerStack stack;
7375
ExecutorService executor;
74-
76+
7577
Producer(InnerStack stack) {
7678
this.stack = stack;
7779
executor = Executors.newSingleThreadExecutor();
@@ -97,7 +99,7 @@ private void produce() {
9799
static class Consumer {
98100
private InnerStack stack;
99101
ExecutorService executor;
100-
102+
101103
Consumer(InnerStack stack) {
102104
this.stack = stack;
103105
executor = Executors.newSingleThreadExecutor();

multithreading/src/main/java/com/rakeshv/locks/ReentrantLocks.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
public class ReentrantLocks {
88
int value = 0;
99
ReentrantLock lock = new ReentrantLock();
10+
1011
public static void main(String[] args) {
1112
ExecutorService executor = Executors.newFixedThreadPool(3);
1213
ReentrantLocks locks = new ReentrantLocks();
@@ -26,7 +27,6 @@ public void increment() {
2627
System.out.println("Count is " + value);
2728
Thread.sleep(1000);
2829
} catch (InterruptedException e) {
29-
// TODO Auto-generated catch block
3030
e.printStackTrace();
3131
} finally {
3232
lock.unlock();

multithreading/src/main/java/com/rakeshv/mythreads/App.java

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -7,17 +7,16 @@
77

88
public class App {
99
public static void main(String[] args) {
10-
Count count = new Count();
1110

1211
for (var i = 0; i < 10; i++) {
13-
Thread thread = new Thread(() -> {
14-
try {
15-
Count.increment();
16-
} catch (InterruptedException e) {
17-
e.printStackTrace();
18-
}
19-
});
20-
thread.start();
12+
Thread thread = new Thread(() -> {
13+
try {
14+
Count.increment();
15+
} catch (InterruptedException e) {
16+
e.printStackTrace();
17+
}
18+
});
19+
thread.start();
2120
}
2221
}
2322

@@ -48,9 +47,9 @@ public static void increment() throws InterruptedException {
4847
if (lock.tryLock(1000, TimeUnit.MILLISECONDS)) {
4948
try {
5049
int current = counter;
51-
System.out.println("Before: " + current + " thread id " + Thread.currentThread().getId());
50+
System.out.println("Before: " + current + " thread id " + Thread.currentThread().threadId());
5251
counter = current + 1;
53-
System.out.println("After: " + counter + " thread id " + Thread.currentThread().getId());
52+
System.out.println("After: " + counter + " thread id " + Thread.currentThread().threadId());
5453
} finally {
5554
lock.unlock();
5655
}

0 commit comments

Comments
 (0)