Reputation: 8112
I noticed some frameworks throw an exception when you try to access objects or properties from a different thread than the main thread.
What is a suitable way to detect and throw an exception if my object (or a method in my object) is accessed from a different thread than the one that created it. Is there some notion of a thread "owning" an object?
Upvotes: 2
Views: 430
Reputation: 27190
No. The language and the libraries have no concept of threads "owning" any object. You can implement it yourself easily enough:
class MyClass {
final Thread owner;
MyClass() {
owner = Thread.currentThread();
}
void assertOwnership() {
if (Thread.currentThread() != owner) {
throw new RuntimeException("Current thread does not own: " + this);
}
}
}
Edit: But what problem are you really trying to solve? One of the essential facts about threads is that they all operate in the same address space, and they all have equal access to the same data. Why do you care which thread "owns" a given object? What is the exception supposed to mean when one thread accesses an object that it doesn't "own?"
Upvotes: 1
Reputation: 7054
You can use thread local data to enforce this. The framework inserts thread local variable on the main thread. When you invoke the framework it looks to see if the thread local variable exists. If it doesn't then it throws an exception.
Look at the ThreadLocal class or this tutorial
Upvotes: 0