rewrite
rewrite copied to clipboard
`Thread.notifyAll` should be used. `RSPEC-2446`
notify and notifyAll both wake up sleeping threads, but notify only rouses one, while notifyAll rouses all of them. Since notify might not wake up the right thread, notifyAll should be used instead.
See : https://rules.sonarsource.com/java/quickfix/RSPEC-2446
Examples From : https://wiki.sei.cmu.edu/confluence/display/java/THI02-J.+Notify+all+waiting+threads+rather+than+a+single+thread
public final class ProcessStep implements Runnable {
private static final Object lock = new Object();
private static int time = 0;
private final int step; // Do Perform operations when field time
// reaches this value
public ProcessStep(int step) {
this.step = step;
}
@Override public void run() {
try {
synchronized (lock) {
while (time != step) {
lock.wait();
}
// Perform operations
time++;
lock.notify();
}
} catch (InterruptedException ie) {
Thread.currentThread().interrupt(); // Reset interrupted status
}
}
public static void main(String[] args) {
for (int i = 4; i >= 0; i--) {
new Thread(new ProcessStep(i)).start();
}
}
}```
public final class ProcessStep implements Runnable {
private static final Object lock = new Object();
private static int time = 0;
private final int step; // Perform operations when field time
// reaches this value
public ProcessStep(int step) {
this.step = step;
}
@Override public void run() {
try {
synchronized (lock) {
while (time != step) {
lock.wait();
}
// Perform operations
time++;
lock.notifyAll(); // Use notifyAll() instead of notify()
}
} catch (InterruptedException ie) {
Thread.currentThread().interrupt(); // Reset interrupted status
}
}
}