IUnknown
IUnknown

Reputation: 9827

Using UNSAFE in collections

I notice that in Java 7 ,the collection classes(ConcurrentLinkedQueue in my case) use UNSAFE class for swap and find operations.
The offset seems to be calculated on the compile time declaration:

itemOffset = UNSAFE.objectFieldOffset(local.getDeclaredField("item"));

How would this work in a scenario where we do not have the exact parametrized type at compile time e.g when we try to insert an apple in to a method having Collection<? super Apple> in the declaration.

Does it use 'Apple' as the declared class to calculate offset?
Would appreciate any help in understanding the way UNSAFE works to calculate offsets here.

Upvotes: 1

Views: 191

Answers (1)

axtavt
axtavt

Reputation: 242716

Jave doesn't allow us to use primitive types as type parameters of generics, only reference types are allowed. Reference types are stored as references that always have the same size, so that internal representation of objects of certain generic class is always the same, no matter how they're parameterized.

Therefore exact type of collection's items doesn't matter, because item is a reference that always has the same size.

Upvotes: 3

Related Questions