Question
How can one Java thread wait for another thread's output without wasting CPU cycles?
// Code example will be included in the explanation.
Answer
In Java, managing thread coordination is crucial, especially when one thread's output or state is dependent on another thread's execution. In your case, you need the application logic thread to wait for the database access thread to be ready without wasting CPU resources on busy waiting. This can be achieved through various synchronization mechanisms in Java, such as using the wait-notify model or CountDownLatch.
import java.util.concurrent.CountDownLatch;
public class ThreadCoordination {
static CountDownLatch readyLatch = new CountDownLatch(1);
static class DatabaseThread extends Thread {
@Override
public void run() {
try {
// Simulating some initialization work.
Thread.sleep(2000);
// Indicate that the db is ready.
readyLatch.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
static class AppThread extends Thread {
@Override
public void run() {
try {
// Wait until the db thread signals it is ready.
readyLatch.await();
System.out.println("Database is ready. Proceeding with application logic...");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
DatabaseThread dbThread = new DatabaseThread();
AppThread appThread = new AppThread();
dbThread.start();
appThread.start();
}
}
Causes
- The application logic thread requires a signal or state change from the database access thread before proceeding.
- Busy waiting, like polling with a while loop, causes unnecessary CPU consumption.
Solutions
- **Using Wait and Notify**: Implement a `wait` and `notify` mechanism where the app thread waits until the db thread notifies it that it's ready.
- **Using CountDownLatch**: This is a simpler approach where the database thread would count down when it's ready, allowing the application thread to proceed when the count reaches zero.
Common Mistakes
Mistake: Using a while loop to check if a thread is ready, causing high CPU usage.
Solution: Use synchronization methods like wait-notify or CountDownLatch for efficient thread usage.
Mistake: Not handling InterruptedException during wait or await calls.
Solution: Implement proper exception handling to maintain thread safety.
Helpers
- Java thread synchronization
- Java wait notify example
- CountDownLatch Java
- thread coordination in Java
- Java concurrency best practices