Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why AtomicInteger is abstract in Kotlin? (it works fine in Java)

I was trying to make something similar to this(actually you don't need to read the link to understand this question, it's just for reference), and I write this:

class CallArbiter: AtomicInteger { // error
  constructor(initialValue: Int) : super(initialValue)
  constructor() : super()
}

The compiler says:

Error:(8, 1) Kotlin: Class 'CallArbiter' must be declared abstract or implement abstract base class member public abstract fun toByte(): Byte defined in java.util.concurrent.atomic.AtomicInteger

I can't figure out why it requires me to implement those methods. I didn't see them in the AtomicInteger class. Everything is fine in Java.

like image 649
ice1000 Avatar asked Aug 26 '17 12:08

ice1000


People also ask

Why AtomicInteger is used in Java?

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.

How does Java AtomicInteger work?

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.

How do you declare AtomicInteger in Java?

AtomicInteger atomicInteger = new AtomicInteger(); This example creates an AtomicInteger with the initial value 0 . If you want to create an AtomicInteger with an initial value, you can do so like this: AtomicInteger atomicInteger = new AtomicInteger(123);

What is AtomicInteger and how it is useful in concurrent environment?

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.


1 Answers

AtomicInteger extends java.lang.Number, but in Kotlin this type is mapped to kotlin.Number.

In kotlin.Number these abstract methods are defined (which you can see in its API):

toByte, toInt, toChar etc.

If you debug this line of code: AtomicInteger(2).toByte() you can see, that the method java.lang.Number::byteValue is used, this is done by using certain compiler techniques.

like image 160
s1m0nw1 Avatar answered Sep 28 '22 12:09

s1m0nw1