1

Simple question, for the sake of theory, and could not find anything that addressed this particular usecase:

One method, called by 40 000 Threads ( For the sake of being relevant question )

public void synced() {
    synchronized(lock) { number *= 1.23; }
}

public void atomic() {
     number.updateAndGet(n -> n*1.23) 
}

Which one is likely to cause less issues here?

I am thinking that the atomic method would, since updateAndGet uses a while loop internally and if we have high access to the updateAndGet method, many threads could end up in that while loop, and possibly exiting very late in worst case scenario, if at all.

The first case won't, although lack of a fairness policy could prevent it from running late as well.

mjs
  • 21,431
  • 31
  • 118
  • 200
  • By 'less issues' do you mean less contention? – pedromss Sep 01 '17 at 13:10
  • @pedromss any view point and angle is worth hearing and exloring. I am not really sure what contention actually means either. Both I guess are thread safe, however, the atomic one has what appears to be a pitfall, where one thread can get to run yet, not complete. synchronized does not, right? If you get to run then you complete. However, I am not sure if synchronized would be much slower to use or more expensive or not. If not, then I would opt to use that version. Of course, it might be irrelevant in real world cases, but theory is fun to get right. – mjs Sep 01 '17 at 13:13
  • I guess the fundamental question here is given high concurrency levels, would synchronized be more wise to use? Note that, standard increment functin does not seem to perform in a while loop like getAndUpdate. – mjs Sep 01 '17 at 13:14
  • @momomo I actually wanted to provide an answer here, but while writing it discovered something that I had not known... https://stackoverflow.com/questions/46092685/cas-vs-synchronized-performance – Eugene Sep 07 '17 at 11:30
  • @Eugene It could be an answer here too. I will reply on your post. – mjs Sep 07 '17 at 19:59
  • 1
    @momomo Deleting my answer here in favor of a much more complete one in Eugene's question [here](https://stackoverflow.com/a/46099761/2716383) – pedromss Sep 08 '17 at 17:26

0 Answers0