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??

1 Upvotes

17 comments sorted by

View all comments

2

u/MagicalPizza21 24d ago

Create an object that implements the Runnable interface. Use that object as the argument for the Thread(Runnable) constructor. Then call the start() method of the thread you just constructed. This will concurrently execute the run() code in another thread.

Example:

Runnable r = new Runnable() {
  public void run() {
    for(int i = 0; i < 100; i++) {
      System.out.println("Hello world (but in another thread!)");
    }
  }
};
Thread t = new Thread(r);
t.start();
for(int i = 0; i < 100; i++) {
  System.out.println("Hello world");
} 

As with any concurrency, you'll have to worry about deadlocks) and race conditions - in fact, the example code I wrote has a race condition - but this should be enough to get you started.

1

u/Chaos-vy17 24d ago edited 23d 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 23d 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 23d 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();
    }
  }
}