Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AtomicInteger.incrementAndGet() vs. AtomicInteger.getAndIncrement()

When return value is not of interest, is there any (even irrelevant in practice) difference between AtomicInteger.getAndIncrement() and AtomicInteger.incrementAndGet() methods, when return value is ignored?

I'm thinking of differences like which would be more idiomatic, as well as which would put less load in CPU caches getting synchronized, or anything else really, anything to help decide which one to use more rationally than tossing a coin.

like image 715
hyde Avatar asked Feb 28 '13 13:02

hyde


People also ask

What is difference between Integer and AtomicInteger?

Integers are object representations of literals and are therefore immutable, you can basically only read them. AtomicIntegers are containers for those values. You can read and set them. Same as asigning a value to variable.

What is AtomicInteger and when to use?

AtomicInteger class provides operations on underlying int value that can be read and written atomically, and also contains advanced atomic operations. AtomicInteger supports atomic operations on underlying int variable. It have get and set methods that work like reads and writes on volatile variables.

Why is AtomicInteger class better than a synchronized counter class What is CAS?

AtomicInteger uses combination of volatile & CAS (compare and swap) to achieve thread-safety for Integer Counter. It is non-blocking in nature and thus highly usable in writing high throughput concurrent data structures that can be used under low to moderate thread contention.

Is AtomicInteger slow?

AtomicInteger is slower than synchronized.


1 Answers

Since no answer to the actual question has been given, here's my personal opinion based on the other answers (thanks, upvoted) and Java convention:

incrementAndGet() 

is better, because method names should start with the verb describing the action, and intended action here is to increment only.

Starting with verb is the common Java convention, also described by official docs:

"Methods should be verbs, in mixed case with the first letter lowercase, with the first letter of each internal word capitalized."

like image 50
hyde Avatar answered Sep 28 '22 04:09

hyde