I’ve run into an issue where instanceof works, and then it doesn’t. Going into details is difficult, but I think this might be the problem:
Reading this: http://www.theserverside.com/news/thread.tss?thread_id=40229 (search for Thread.currentThread), it seems to imply that, even if the two objects are the same class, if you pass them between threads with different class loaders, instanceof (and isAssignableFrom) might still fail.
This certainly would explain the behavior I’m having, but I was wondering if anyone could verify it?
(I wish the article linked at the beginning of the discussion was still available, but it doesn’t seem like it is.)
This has nothing to do with threads, only with class loaders. The same class definition, when loaded by different classloaders, is seen as two different classes by the JVM. So
instanceofor casts between the two fail.So to answer your original question: passing objects between threads loaded by the same class loader is safe and
instanceofet al. works fine.Here is an article about class loading issues.
See also this earlier answer of mine for a way to verify which classloaders are in the game.
Update to Romain’s comment
Here is some code to test the behaviour of
instanceof, among others:And the output is (in Eclipse, Java5):
So everything seems to be consistent 🙂