KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
Warning: the question is a little long, but the part below the separation line is for curiosity only. Oracle's JDK 7 implementation of AtomicInteger includes the following methods: public final int addAndGet(int delta) { for (;;) { int current = get(); int next = current + delta; // Only difference if (compareAndSet(current, next)) return next; } } public final int incrementAndGet() { for (;;) { int current = get(); int next = current + 1; // Only difference if (compareAndSet(current, next)) return next; } } It seems clear that the second method could have been written: public final int incrementAndGet() { return addAndGet(1); } There are several other examples of similar code duplication in that class. I can't think of any reasons to do that but performance considerations (*). And I am pretty sure the authors did some in-depth testing before settling on that design. Why (or in what circumstances) would the first code perform better than the second? (*) I could not resist but write a quick micro benchmark. It shows (post-JIT) a systematic gap of 2-4% performance in favour of addAndGet(1) vs incrementAndGet() (that is admittedly small, but it is very consistent). I can't really explain that result either to be honest... Output: incrementAndGet(): 905 addAndGet(1): 868 incrementAndGet(): 902 addAndGet(1): 863 incrementAndGet(): 891 addAndGet(1): 867 ... Code: public static void main(String[] args) throws Exception { final int size = 100_000_000; long start, end; AtomicInteger
Tags (comma-separated)
Save Edits
Cancel