Hinton
Hinton

Reputation: 2390

Spring Creates New Objects But Should Not

I'm having the following problem with Spring: I expected that singletons would be created once and then referenced from the Spring cache. But that does not seem to be the case. I have the following lines in my beans.xml:

<bean id="Cache" class="java.util.HashMap" scope="singleton" >
</bean>

which is referenced below like:

<bean id="ManuallyCachingDAO" class="blah"
scope="singleton" init-method="init" destroy-method="destroy">
    <property name="cache" ref="Cache"></property>
    ...

and in the ManuallyCachingDAO the code:

public Object get(int id) {
    Object o = cache.get(id);
    if (o != null) {
        return o;
    }
    // ... code for retrieving the object from the DB
}

but the HashMap gets emptied in mysterious ways sometimes! That is, I don't think it's actually emptied. I think it's just dropped and created anew when I reference the ManuallyCachingDAO in another class.

Could you tell me how to fix this problem?

EDIT: At Robin's hint: I do the following to get the beans in a lot of classes (not all though):

ClassPathResource blah = etc.; 
XmlBeanFactory xbf = new XmlBeanFactory(blah); 
...
xbf.getBean("Cache");

... right now I'm doing it (even for a lot of other beans) ... is that a very stupid or very bad idea or both? I think it occurs to me right now what I'm doing wrong... Until now, I just suspected that all XmlBeanFactories were somehow grabbing the same resources which might have been very dumb indeed, or could s/o tell me what's right?

Upvotes: 0

Views: 166

Answers (3)

dagge
dagge

Reputation: 1155

Maybe concurrency is messing up your map. You don't want to use a HashMap as a singleton since it's not thread safe. Try using ConcurrentHashMap instead.

Upvotes: 2

Robin
Robin

Reputation: 24272

The config looks fine, and Spring is well tested in this respect so I don't think there are going to be any surprises there.

Would you by any chance be creating the Spring context each time you are trying to access the beans? Thereby recreating everything repeatedly.

Upvotes: 1

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 299048

I doubt that Spring is creating new HashMaps. Your configuration looks OK. I am pretty sure something is wrong in your logic.

In the part marked

// ... code for retrieving the object from the DB

do you actually write the retrieved values to the map?

Upvotes: 2

Related Questions