Question

Looking through some java code and this just does not seem right. To me, it looks like every time you call projects, you will get a new hashmap, so that this statement is always false

projects.get(soapFileName) != null

Seems like it should have a backing field

public static HashMap<String,WsdlProject> projects = new HashMap<String,WsdlProject>();

public Object[] argumentsFromCallSoapui(CallT call, Vector<String> soapuiFiles, HashMap theDPLs,int messageSize)
{
    try {
        for (String soapFileName:soapuiFiles){
            System.out.println("Trying "+soapFileName);
            WsdlProject project ;
            if (projects.get(soapFileName) != null){
                project = projects.get(soapFileName);
            } else {
                project = new WsdlProject(soapFileName);
                projects.put(soapFileName,project);
            }
        }
    } ...
}
Was it helpful?

Solution

Nope. In Java that static variable only gets initialized once.

So, this line will only get called once.

public static HashMap<String,WsdlProject> projects = new HashMap<String,WsdlProject> ();

OTHER TIPS

The projects variable will be initialized once, when the class first loads.

Generally, static maps of this sort are a bad idea: they often turn into memory leaks, as you hold entries long past their useful life.

In this particular case, I'd also worry about thread safety. If you have multiple threads calling this method (which is likely in code dealing with web services), you'll need to synchronize access to the map or you could corrupt it.

And, in a general stylistic note, it's a good idea to define variables using the least restrictive class: in this case, the interface Map, rather than the concrete class HashMap.

You don't call projects - it's a field, not a method.

As it's a static field, it will be initialized exactly once (modulo the same type being loaded in multiple classloaders).

if you add a static initialiser (static constructor?) you'll be able to see that statics are just initialised the first time the class is loaded:

public class Hello {
    static { System.out.println("Hello static World!"); }

    ...
}

You won't get a new HashMap every time you invoke a method on projects, if that's what you are referring to. A new HashMap will be created once, however all instances of the class will share a single HashMap.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top