1import java.util.concurrent.*;
2import java.util.stream.*;
3
4public class AdvancedConcurrency { 5 6 public static void main(String[] args) { 7 // Create an ExecutorService with a fixed thread pool 8 ExecutorService executor = Executors.newFixedThreadPool(4); 910 // Submit Callable tasks to the ExecutorService11 List<Callable<Integer>> tasks =12 List.of(13 () -> {14 return doWork(1);15 },16 () -> {17 return doWork(2);18 },19 () -> {20 return doWork(3);21 },22 () -> {23 return doWork(4);24 });2526 try {27 // Invoke all tasks and collect results in a List<Future<Integer>>28 List<Future<Integer>> results = executor.invokeAll(tasks);2930 // Process results31 for (Future<Integer> result : results) {32 System.out.println(result.get());33 }34 } catch (InterruptedException | ExecutionException e) {35 e.printStackTrace();36 } finally {37 // Shutdown the ExecutorService38 executor.shutdown();39 }4041 // Parallel Stream example42 int sum = IntStream.range(0, 1000000).parallel().reduce(0, Integer::sum);43 System.out.println("Sum: " + sum);44 }4546 private static int doWork(int id) {47 // Simulate some work48 try {49 Thread.sleep(1000);50 } catch (InterruptedException e) {51 e.printStackTrace();52 }53 return id * 2;54 }55}
This class does not have any documentation.
Consider adding a documentation comment to explain its use.
While it may seem like the functionality of a class is perfectly obvious, any consumers of your API may not be able to pick up on certain details.
Bad Practice
Consider a case where the class given below can be instantiated and provides certain functionalities within each instance in a thread-safe manner, perhaps it is a rest API client.
If there is no documentation comment on the class, it is not immediately obvious that the class is thread safe. Thus, multiple instances of the class may be created to perform operations concurrently, using up both memory as well as OS resources like sockets. If it were known from the beginning that the class were thread safe, the user would not need to create unnecessary extra instances of SomeClass
.
class SomeClass {
// ...
}
Recommended
Make sure to add useful information regarding the usage or implementation of a particular declaration, so that anything about it which can't be understood from the name or some other cue is correctly conveyed.
/**
* Instances of this class are used to perform xyz action.
*
* This class is thread safe and the same instance can be used over multiple threads.
*/
class SomeClass {
// ...
}
Exceptions
This issue will not be reported for model entity classes. If there is any non-obvious behavior associated with a particular class however, do consider documenting it.