Skip to content

Instantly share code, notes, and snippets.

@AlexRogalskiy
Forked from NicMcPhee/Counter.java
Created October 25, 2024 08:48
Show Gist options
  • Select an option

  • Save AlexRogalskiy/cb6b27a2e7f246b4f0f42f0c90a3cdc7 to your computer and use it in GitHub Desktop.

Select an option

Save AlexRogalskiy/cb6b27a2e7f246b4f0f42f0c90a3cdc7 to your computer and use it in GitHub Desktop.

Revisions

  1. @NicMcPhee NicMcPhee revised this gist Mar 8, 2016. No changes.
  2. @NicMcPhee NicMcPhee created this gist Nov 20, 2013.
    20 changes: 20 additions & 0 deletions Counter.java
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,20 @@
    public class Counter {

    private int count = 0;

    public int getCount() {
    return count ;
    }

    /**
    * The "synchronized" keyword is crucial here; removing it will lead to serious
    * race conditions on multiple-core computers. Having it ensures that two threads
    * can't enter this method at the same time, making sure that only one thread passes
    * through this method at a time, which ensures that the increments are handled
    * correctly.
    */
    public synchronized void incrementCount() {
    ++count;
    }

    }
    34 changes: 34 additions & 0 deletions SynchronizedIncrement.java
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,34 @@
    public class SynchronizedIncrement implements Runnable {

    private static final int NUM_THREADS = 4;
    private static final int NUM_INCREMENTS = 10000;
    private Counter counter;

    public SynchronizedIncrement(Counter counter) {
    this.counter = counter;
    }

    public static void main(String[] args) throws InterruptedException {
    Thread[] threads = new Thread[NUM_THREADS];
    Counter counter = new Counter();

    for (int i=0; i<NUM_THREADS; ++i) {
    threads[i] = new Thread(new SynchronizedIncrement(counter));
    threads[i].start();
    }

    for (int i=0; i<NUM_THREADS; ++i) {
    threads[i].join();
    }

    System.out.println("total count = " + counter.getCount() + " vs. expected = " + (NUM_THREADS * NUM_INCREMENTS));
    }

    @Override
    public void run() {
    for (int i=0; i<NUM_INCREMENTS; ++i) {
    counter.incrementCount();
    }
    }

    }