views:

370

answers:

5

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);
            }
        }
    } ...
}
+3  A: 

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> ();
jjnguy
A: 

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.

Thomas Owens
+1  A: 

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).

Jon Skeet
He probably meant use : /
AlbertoPL
Quite possibly - but it's an important distinction.
Jon Skeet
+3  A: 

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.

kdgregory
It's not thread-safe. It leaks. It's difficult to test. The root problem is that mutable statics indicate piss poor design.
Tom Hawtin - tackline
Yes, at the very least the implementation should be switched to a ConcurrentHashMap - but even that won't fix the other potential issues.
Bill Michell
+1  A: 

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!"); }

    ...
}
Static initializer
Jim Ferrans