-1

I want to run this asynchronously but all no thread locking , no syncronization also awaitTermination timeout should not be increased.

    @Test
    void arrayCheck() throws InterruptedException {
        final int[] count = {0};
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        for (int i = 0; i <10000; i++) {
            executorService.execute(() ->
            {
                try {
                    Thread.sleep(100);
                    count[0]++;
                    System.out.println(Thread.currentThread().getName()+"----"+count[0]+"---");
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            });
            executorService.awaitTermination(10,TimeUnit.MILLISECONDS);

        }
        Assertions.assertEquals(10000,count[0]);
    }

i have used atomic variables but i have to use array only

  • Not hugely different from your [previous question](https://stackoverflow.com/questions/76685093/how-to-run-threads-asynchrounously-but-get-results-in-synchronous-way-without-us) which you could have edited based on the comments or deleted. – DuncG Jul 14 '23 at 10:12
  • what can i do to solve this problem @DuncG i have made changes – aditya sharma Jul 14 '23 at 10:19
  • 2
    AFAIK it is not possible. – Stephen C Jul 14 '23 at 10:21
  • 1
    (Note that the `AtomicInteger` implementation in Java relies on CAS - compare and swap - or a similar instruction provided by the hardware. `volatile` semantics are not sufficient.) – Stephen C Jul 14 '23 at 10:30
  • You need to explain the problem properly. Even if you resolve updating the counters the final total is never going to be right as you await termination for 10ms but may have 5x runnable each requiring 200ms before they end – DuncG Jul 14 '23 at 10:38
  • i want that when threads are taking over count situation like deadlock or race condition should not occur also the count after 10000 iteration should be 10000 @DuncG – aditya sharma Jul 14 '23 at 10:48
  • If `count` wasn't an array it could be `volatile`. – user207421 Jul 14 '23 at 12:00
  • 1
    Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Jul 14 '23 at 15:51

1 Answers1

1

No, it is not possible to make the ++ operator thread safe without synchronization or locking. This is not an atomic operation, and requires three sub-steps:

  1. reading the current value of the variable
  2. adding one to that value
  3. storing the result back in that variable

In a multi-threaded context, these operations can be interleaved with other threads, meaning that the value of the variable can change between step 1 and step 3 above resulting in a lost update because the same count is stored by more than one thread.

In addition to that, it is never thread safe to access and modify an array concurrently in Java without taking measures to ensure visibility of updates to other threads. See Java volatile array? for details.

The only way to perform an atomic, thread-safe increment operation without locking in Java is to use classes from java.util.concurrent.atomic, such as AtomicInteger or AtomicLong.

Tim Moore
  • 8,958
  • 2
  • 23
  • 34