Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: edits, added annotation to some CSs

...

Synchronizing the code makes it easier to reason about its behavior and is frequently more secure than simply using volatile. However, synchronization has a somewhat higher performance overhead and can result in thread contention and deadlocks when used excessively.

...

Code Block
bgColor#ccccff
final class ControlledStop implements Runnable {
  private volatile boolean done = false;
 
  @Override public void run() {
    while (!done) {
      try {
        // ...
        Thread.currentThread().sleep(1000); // Do something
      } catch(InterruptedException ie) { 
        // Handle exception
        Thread.currentThread().interrupt(); // Reset interrupted status
      } 
    } 	 
  }

  public void shutdown() {
    done = true;
  }
}

...

Code Block
bgColor#ccccff
final class ControlledStop implements Runnable {
  private final AtomicBoolean done = new AtomicBoolean(false);
 
  @Override public void run() {
    while (!done.get()) {
      try {
        // ...
        Thread.currentThread().sleep(1000); // Do something
      } catch(InterruptedException ie) { 
        // Handle exception
        Thread.currentThread().interrupt(); // Reset interrupted status
      } 
    } 	 
  }

  public void shutdown() {
    done.set(true);
  }
}

...

Code Block
bgColor#ccccff
final class ControlledStop implements Runnable {
  private boolean done = false;
 
  @Override public void run() {
    while (!isDone()) {
      try {
        // ...
        Thread.currentThread().sleep(1000); // Do something
      } catch(InterruptedException ie) { 
        // Handle exception
        Thread.currentThread().interrupt(); // Reset interrupted status
      } 
    } 	 
  }

  public synchronized boolean isDone() {
    return done;
  }

  public synchronized void shutdown() {
    done = true;
  }
}

...