Programming Tips - Java: How to do: `public static synchronized int`

Date: 2012jun8 Update: 2025oct14 Language: Java Q. Java: How to do: `public static synchronized int`
public static synchronized int myCounter = 0; // Does NOT work
A. Use AtomicInteger or AtomicLong as shown in this full example:
import java.util.concurrent.atomic.AtomicInteger; class Demo { // This can safely be accessed from multiple threads. public static AtomicInteger myCounter = new AtomicInteger(0); // <-- HERE public static final void main(String[] args) { myCounter.getAndIncrement(); myCounter.getAndIncrement(); final int n = myCounter.getAndIncrement(); System.out.println("n=" + n); } }
Output:
n=2