2

How to make sure that these two concurrent data structure statements get executed as an atomic block without using synchronized statement so that the sum is consistent at any given point in time?

Note : I am new to multi-threading in java.

AtomicLong sumOfAllItems=new AtomicLong();
AtomicLong itemSpecificSum=new AtomicLong();

public void addPrice(long price){
    // how to make sure that these two statements get executed 
    // with synchronised() block

    sumOfAllItems.addAndGet(price);
    itemSpecificSum.addAndGet(price);
}
ernest_k
  • 44,416
  • 5
  • 53
  • 99
Sonu
  • 33
  • 5
  • Why avoid `synchronized`? – Basil Bourque Jan 28 '20 at 07:46
  • I would go with `synchronized` as well. You can get it to work with`java.util.concurrent.locks.Lock` – Christoph Bauer Jan 28 '20 at 07:53
  • Why do you need synchronization? `sumOfAllItems` and `itemSpecificSum` are safe because they are atomic classes. It's good as it is. –  Jan 28 '20 at 07:56
  • Each of the sums are atomic, but he wants the combined statements to be atomic. I'd go with synchronized also. – NomadMaker Jan 28 '20 at 08:04
  • The comment in the code suggests to use `synchronized` as well – Christoph Bauer Jan 28 '20 at 08:08
  • @NomadMaker What's the point of make them atomic? –  Jan 28 '20 at 08:08
  • You can imagine a method in a different thread that gets both values and performs some computation on them, and expects them to be updated at the same time. IMO very reasonable to want this block to be `symchronized`. I am however confused by wanting to avoid using `synchronized`... – cameron1024 Jan 28 '20 at 08:23
  • The reason for making it atomic is that there are two background services that return both the results and I want the ```sumOfAllItems``` to be equal to aggregated sum of all ```itemSpecificSum``` at any given point in time. – Sonu Jan 28 '20 at 10:26
  • Your question says *without* but in your code you say *with* `synchronized`. One is a typo, please check and correct. – Zabuzard Jan 29 '20 at 00:05

1 Answers1

1

Change your method from this:

public void addPrice(long price) {
    // ...    
}

to this:

public synchronized void addPrice(long price) {
    // ...    
}

By designating the method as sychronized, the JVM will allow no more than one thread at a time to execute that method.

There are other ways of writing thread safe code, but unless and until you have a specific reason to use them, using synchronized it great – it's simple, correct, and easy to understand / reason about.

Kaan
  • 5,434
  • 3
  • 19
  • 41