Skip to content

Instantly share code, notes, and snippets.

@DhavalDalal
Last active February 17, 2022 10:24
Show Gist options
  • Save DhavalDalal/9e2f0f70a59d99fdbc5a53644810d5be to your computer and use it in GitHub Desktop.
Save DhavalDalal/9e2f0f70a59d99fdbc5a53644810d5be to your computer and use it in GitHub Desktop.
Thread-Safe Counter (Java)

Thread-Safe Counter (Java)

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());
}
}
@DhavalDalal
Copy link
Author

that's correct

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment