I am making an application that takes a bunch of journal entries and calculate sum.
Is below way of doing it is thread/concurrency safe when there are multip
That is not safe, because threads A and B might both call sumByAccount.get(account) at the same time (more or less), so neither one will see the result of the other's add(amount). That is, things might happen in this sequence:
sumByAccount.get("accountX") and gets (for example) 10.0.sumByAccount.get("accountX") and gets the same value that thread A did: 10.0.newSum to (say) 10.0 + 2.0 = 12.0.newSum to (say) 10.0 + 5.0 = 15.0.sumByAccount.put("accountX", 12.0).sumByAccount.put("accountX", 15.0), overwriting what thread A did.One way to fix this is to put synchronized on your addToSum method, or to wrap its contents in synchronized(this) or synchronized(sumByAccount). Another way, since the above sequence of events only happens if two threads are updating the same account at the same time, might be to synchronize externally based on some sort of Account object. Without seeing the rest of your program logic, I can't be sure.