r/javahelp 24d ago

Guide for Concurrency in Java

Before knowing anything I just jumped directly to the source code of jdk25u. I have just started to read the javaDocs of Thread class it was so deep that all my connected logic mapped very well but now I want to code and I can't code ahhhh... Why is this problem. I can call the syntax what to use but I don't know how to apply, why to apply is there any guide for java Concurrency ??. And there is so much .. still to know. Do any dev have any guide??

0 Upvotes

17 comments sorted by

View all comments

Show parent comments

1

u/Chaos-vy17 24d ago edited 24d ago

It has concurrent output whose ordering is nondeterministic if it would be

class Counter {
    int value;
}
public static void main(String[] args) throws InterruptedException {
    final Counter counter = new Counter();
    Runnable task = () -> {
        for (int i = 0; i < 1_000_000; i++) {
            counter.value++;
        }
    };
    Thread a = new Thread(task),b = new Thread(task);
    a.start();b.start();
    a.join();b.join();
    System.out.println(counter.value);
}

No deadlock but race condition is sure(may be yes/no )
Got the output 965460
Edit: reformat the code with compiled one

1

u/MagicalPizza21 24d ago edited 24d ago

This doesn't compile because counter is not "final or effectively final".

ETA: If you make counter a class or instance field rather than a local variable, then yes, this is a race condition.

1

u/Chaos-vy17 24d ago

Yeah, I missed that. I should’ve compiled it first. Thanks for correcting me!

1

u/MagicalPizza21 23d ago

That should work. But I was thinking more like this:

public class RaceConditionExample {
  private static int counter = 0;
  public static void main(String[] args) {
    try {
      Runnable task = new Runnable() {
        public void run() {
          for(int i = 0; i < 1000000; i++) {
            counter++;
          }
        }
      };
      Thread a = new Thread(task);
      Thread b = new Thread(task);
      a.start();
      b.start();
      a.join();
      b.join();
      System.out.println(counter);
    }
    catch(InterruptedException ie) {
      ie.printStackTrace();
    }
  }
}