Reputation: 21978
Is sun.misc.Unsafe
or the theUnsafe
instance thread safe?
Upvotes: 1
Views: 1079
Reputation: 3224
The accepted answer is at least misleading if not wrong.
On the Java level, Unsafe
does not hold any instance state. Most of its methods call native code, which either does not work with any shared mutable state or it calls to the native allocator to allocate/free memory and those operations are thread safe (usually you don't synchronize calls to new
C++, for example). OTOH, sun.misc.Unsafe
is internal API and its contract is not documented and may change.
Do you need to synchronize calls to methods on the Unsafe
instance? That depends on whether you may be passing in the same addresses as the arguments to those methods. In the same way as calls to the addItem
method of the following Java class need to be synchronized if you are passing to it the same list from different threads.
class ListUtils {
public static void addItem(List<Object> list, Object obj) { list.add(obj); }
}
// Good:
// thread1:
List<Object> l1 = new List<>();
ListUtils.addItem(l1, 1);
// thread2:
List<Object> l2 = new List<>();
ListUtils.addItem(l2, 2);
// Needs synchronization:
class SharedState {
public static List<Object> sharedList = new List<>();
}
// thread1:
ListUtils.addItem(SharedState.sharedList, 1);
// thread2:
ListUtils.addItem(SharedState.sharedList, 2);
I would not say that ListUtils
is not thread-safe. It does not carry any mutable and potentially shared state. Yes, synchronizing the addItem
method would remove the need for synchronization in the second example, but that would unnecessarily synchronize operations that are working with completely different data.
Upvotes: 4
Reputation: 892
The methods of Unsafe
are not thread safe. You need to synchronize access to data you want to manipulate yourself - as usual. Accessing the instance theUnsafe
however is, because the field gets initialized when the class is being loaded (it's static).
Upvotes: 4