JAVA PROGRAM • LEVEL 15 — MULTITHREADING & CONCURRENCY

Protect a Shared Counter in Java

Learn protect a shared counter in java with a complete, compiler-ready Java 17 example.

AdvancedsynchronizedRace condition

PROBLEM UNDERSTANDING

Input and expected output

Sample input
No input required
Sample output
2000

COMPLETE JAVA 17 PROGRAM

Complete Java 17 implementation

java-synchronized-counter.java
Open in compiler
class Counter{private int value; synchronized void increment(){value++;}int value(){return value;}}
class Main{public static void main(String[] args)throws Exception{Counter counter=new Counter();Thread a=new Thread(()->{for(int i=0;i<1000;i++)counter.increment();});Thread b=new Thread(()->{for(int i=0;i<1000;i++)counter.increment();});a.start();b.start();a.join();b.join();System.out.println(counter.value());}}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

2000
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Initialize the deterministic sample values used for protect a shared counter in java.
  2. Create the required object and apply synchronized and Race condition to its state or behavior.
  3. Print the final result and compare it with the documented sample output.

This Java 17 example demonstrates synchronized and Race condition through a complete, executable program. The values are intentionally small so students can trace each statement, verify the output, and then modify the example safely in the online compiler.

EFFICIENCY

Time and space complexity

Time complexity

O(n)

Auxiliary space

O(1)

DEBUGGING CHECKLIST

Common mistakes

Check this

Keep the class name Main and the entry method signature public static void main(String[] args) when using the online compiler.

Check this

Create an object before accessing instance members; static members can be accessed through the class name.

Check this

Java is case-sensitive, and every statement that requires a semicolon must end with one.

Try it yourself

Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.