Creating parallel threads for processing
You're developing a financial analysis application that needs to process a large number of transactions. Each transaction requires CPU-intensive calculations. The application currently uses a sequential approach, but it's too slow. You are tasked with implementing a multi-threaded solution to improve the performance.
This exercise is part of the course
Optimizing Code in Java
Exercise instructions
- Create
Thread
s that will runprocessTransaction()
. - Start all threads.
- Wait for all threads to complete.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
import java.util.*;
public class TransactionProcessor {
public static void main(String[] args) throws InterruptedException {
List transactions = generateTransactions(1000);
List threads = new ArrayList<>();
for (int t = 0; t < 4; t++) {
int start = t * 250;
int end = (t == 3) ? transactions.size() : (t + 1) * 250;
// Create thread that will run processTransaction()
Thread thread = new ___(() -> {
for (int i = start; i < end; i++) {
processTransaction(transactions.get(i));
}
});
threads.add(thread);
// Start the thread
thread.___;
}
// Wait for all threads to complete
for (Thread thread : threads) {
thread.___;
}
}
static void processTransaction(Transaction tx) {
double result = 0;
for (int i = 0; i < 1000; i++) {
result += Math.sqrt(tx.amount * i);
}
tx.result = result;
}
static List generateTransactions(int n) {
List list = new ArrayList<>();
for (int i = 0; i < n; i++) {
list.add(new Transaction(Math.random() * 1000));
}
return list;
}
static class Transaction {
double amount, result;
Transaction(double amount) {
this.amount = amount;
}
}
}