There's a piece of code that looks like this. The problem is that during bootup, 2 initialization takes place. (1) Some method does a reflection on ForumRepository
& performs a newInstance() purely to invoke #setCacheEngine
. (2) Another method following that invokes #start()
. I am noticing that the hashCode of the #cache
member variable is different sometimes in some weird scenarios. Since only 1 piece of code invokes #setCacheEngine
, how can the hashCode change during runtime (I am assuming that a different instance will have a different hashCode). Is there a bug here somewhere ?
public class ForumRepository implements Cacheable
{
private static CacheEngine cache;
private static ForumRepository instance;
public void setCacheEngine(CacheEngine engine) { cache = engine; }
public synchronized static void start()
{
instance = new ForumRepository();
}
public synchronized static void addForum( ... )
{
cache.add( .. );
System.out.println( cache.hashCode() );
// snipped
}
public synchronized static void getForum( ... )
{
... cache.get( .. );
System.out.println( cache.hashCode() );
// snipped
}
}
The whole system is wired up & initialized in the init
method of a servlet.
And the init() method looks like this conceptually:
// create an instance of the DefaultCacheEngine
cache = (CacheEngine)Class.forName( "com..DefaultCacheEngine" ).newInstance();
cache.init();
// init the ForumRepository's static member
Object o = Class.forName( "com.jforum....ForumRepository" ).newInstance();
if( o instanceof Cacheable )
((Cacheable)o).setCacheEngine(cache);
// Now start the ForumRepository
ForumRepository.start();
UPDATE I didn't write this code. It is taken from jforum
UPDATE 2 Solution found. I added a separate comment below describing the cause of the problem. Thanks to everyone.