Private Final Lock Object
Guard mutable list state with a private final lock object instead of synchronized(this) so outside code cannot interfere with the monitor.
Code
import java.util.ArrayList;
import java.util.List;
public class PrivateLock {
private final List<String> events = new ArrayList<>();
// private lock object: outside code cannot obtain the reference, so it cannot synchronize on the same monitor and cut in line
private final Object lock = new Object();
public void record(String event) {
synchronized (lock) {
events.add(event);
}
}
public int size() {
synchronized (lock) {
return events.size();
}
}
public static void main(String[] args) throws InterruptedException {
PrivateLock counter = new PrivateLock();
Runnable worker = () -> {
for (int i = 0; i < 1000; i++) {
counter.record("event-" + i);
}
};
Thread first = new Thread(worker);
Thread second = new Thread(worker);
first.start();
second.start();
first.join();
second.join();
// two threads, 1000 increments each; the lock guarantees atomicity and visibility, so the total is exact
System.out.println("events recorded: " + counter.size());
}
}How it works
The moving parts are the class PrivateLock and the functions record and size.
Iteration happens inside for (int i = 0; i < 1000; i++) — everything outside it runs once.
What to watch for
- The toolchain by itself is enough — no dependency resolution runs.
Using it
The main signature, verbatim, is public void record(String event)
The file’s output announces each step as it happens: events recorded:.
Running the file executes main, which drives record and size in order.
The key statements that remain
Thread second = new Thread(worker);
Thread first = new Thread(worker);
synchronized (lock) {
events.add(event);
}
Interactive Tools for This Topic
FAQ
- What does Private Final Lock Object print when run?
- The script runs standalone; its 1 labeled outputs include `events recorded:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.