Home » Java » multithreading – Java Threads – Keep function in sync with multiple returning values from threads-Exceptionshub

multithreading – Java Threads – Keep function in sync with multiple returning values from threads-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

This is just a concept :

  • I want to have a int be updated, by a function that is running inside multiple threads.
  • My function randomly chooses an int and checks if it’s bigger than the existing int.
  • If so it updates the variable.

How do I ensure my values never clash or my function is looking at an older value not yet updated?

I’m new to threads so any information is valuable.

How to&Answers:

This a job for AtomicInteger!

AtomicInteger atomic;
...
int newValue = atomic.accumulateAndGet​(rand, Math::max);

Answer:

How do I ensure my values never clash?

If you are new to threads, then I would say, use a synchronized block:

final Object lock = new Object();
int global_r = 0;
...
while (true) {
    int r = random.nextInt();
    synchronized(lock) {
        if (r > global_r) {
            global_r = r;
            break;
        }
    }
}

Only one thread at a time can enter the synchronized(lock)... block. A thread that tries when another thread already is in it will be forced to wait.

One should always try to have threads spend as little time as possible inside a synchronized(...) block, which is why I generate the random number outside of the block, and only do the test and the assignment inside it.


Another answer here suggests that you use AtomicInteger. That works too, but it is not what I would recommend for somebody who is taking their very first steps toward understanding how to use threads.