Last active
February 17, 2022 10:24
-
-
Save DhavalDalal/9e2f0f70a59d99fdbc5a53644810d5be to your computer and use it in GitHub Desktop.
Thread-Safe Counter (Java)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.concurrent.locks.*; | |
class Counter { | |
private final ReentrantLock lock = new ReentrantLock(true); | |
private volatile long count = 0; | |
public void increment() { | |
System.out.println(String.format("Acquiring Lock…%s", | |
Thread.currentThread().getName())); | |
lock.lock(); | |
System.out.println(String.format("Acquired Lock %s", | |
Thread.currentThread().getName())); | |
try { | |
count++; | |
} finally { | |
System.out.println(String.format("Releasing Lock...%s", | |
Thread.currentThread().getName())); | |
lock.unlock(); | |
System.out.println(String.format("Released Lock %s", | |
Thread.currentThread().getName())); | |
} | |
} | |
public long value() { | |
return count; | |
} | |
public static void main(String[] args) throws Exception { | |
final Counter counter = new Counter(); | |
final Runnable incrementor = () -> counter.increment(); | |
final Thread thread1 = new Thread(incrementor, "Thread#1"); | |
final Thread thread2 = new Thread(incrementor, "Thread#2"); | |
thread1.start(); | |
thread2.start(); | |
System.out.println("counter.value() = " + counter.value()); | |
Thread.sleep(100); | |
System.out.println("counter.value() = " + counter.value()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
that's correct