Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does AtomicInteger implements Serializable

Accoriding to javadoc,

public class AtomicInteger extends Number implements java.io.Serializable {

// code for class

}

But,

public abstract class Number implements java.io.Serializable {
//code for class
}

If Number class already implements java.io.Serializable then why do AtomicInteger implements it again?

Edit: Does Serializable being a marker interface makes any difference in this context?

like image 973
Priyank Doshi Avatar asked Jun 14 '12 07:06

Priyank Doshi


People also ask

How does AtomicInteger work in Java?

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.

What is AtomicInteger and when to use?

An AtomicInteger is used in applications such as atomically incremented counters, and cannot be used as a replacement for an Integer . However, this class does extend Number to allow uniform access by tools and utilities that deal with numerically-based classes.

Why do we use atomic integers?

The primary use of AtomicInteger is when you are in a multithreaded context and you need to perform thread safe operations on an integer without using synchronized . The assignation and retrieval on the primitive type int are already atomic but AtomicInteger comes with many operations which are not atomic on int .

How do you initialize AtomicInteger in Java?

Setting the AtomicInteger Value set() example: AtomicInteger atomicInteger = new AtomicInteger(123); atomicInteger. set(234); This example creates an AtomicInteger example with an initial value of 123, and then sets its value to 234 in the next line.


2 Answers

Just to document it more clearly. Same situation with the abstract collection base classes.

Could also have been a mistake initially (that is now carried forward for consistency's sake).

like image 100
Thilo Avatar answered Sep 17 '22 17:09

Thilo


There is no necessity as such, it is just for the sake of documentation.

like image 27
Dhwaneet Bhatt Avatar answered Sep 17 '22 17:09

Dhwaneet Bhatt