user1877082
user1877082

Reputation: 471

Is using AtomicInteger in a java multithreading program slower and inefficient than other methods of synchronization?

I am carrying out an experiment with two multithreading java programs. I have one that is not synchronized and another that is using AtomicInteger. The AtomicInteger is much slower. I think this might be because of the method AtomicInteger uses compareAndset(). Am I correct?

Upvotes: 1

Views: 449

Answers (2)

erickson
erickson

Reputation: 269877

The AtomicInteger class and its siblings will be as fast as any equivalent functionality you can write in pure Java, and will often be faster, because they are likely to be able to use native instructions available on the platform.

Whenever you are writing a concurrent program, use the java.util.concurrency package. It's more robust and more efficient than anything you'll write with synchronized or volatile.

An operation by one thread is only guaranteed to be visible to another thread if both threads use suitable memory barriers. For example, writing and reading a volatile variable, or entering a synchronized block. Skipping memory barriers will be faster, but since your program is broken, your efficiency is zero.

Upvotes: 1

reprogrammer
reprogrammer

Reputation: 14728

Of course, the safety of synchronization comes with some performance cost. For example, see Cost of synchronization.

Upvotes: 1

Related Questions