MRenauld
MRenauld

Reputation: 35

Why is my static var not initialized when accessing it through a static method?

I have the following Java class:

public class CWTokenMap {
    public static ConcurrentMap<String, String> allTokens
        = new ConcurrentHashMap<String, String>();

    public static void putTokenData(final String token, final String user) {
        allTokens.put(token, user);
    }
}

When I run my application, I try to access the putTokenData method from another class and I get a NullPointerException for the line allTokens.put(...). Why do I get this exception?

It was my understanding that the static ConcurrentMap should be initialized by the time we access the putTokenData method, but here it seems to not be the case. Are there cases where the static method will be called before initializing the static variable?

Upvotes: 0

Views: 98

Answers (5)

Peter Lawrey
Peter Lawrey

Reputation: 533492

Are there cases where the static method will be called before initializing the static variable?

Yes, you can do this from a static initializer block.

static {
   callMethod(); // this will blow up as `c` has not been initialized yet.
}

static final Collection c = ...;

static void callMethod() {
    c.size();
}

Upvotes: 3

cigno5.5
cigno5.5

Reputation: 712

javadoc says: "Throws: NullPointerException - if the specified key or value is null"

Upvotes: 0

Teo
Teo

Reputation: 3213

Yours statica variable is initialized, the problem as you write in the comment is that token, the key of hasmap is null..

The key can't be null!!

Read here ConcurrentHasMap guide, as you can read: this class does NOT allow null to be used as a key or value.

Upvotes: 0

Rohit Jain
Rohit Jain

Reputation: 213223

You're not getting the NPE due to allTokens. That certainly would have been initialized, by the time the method is invoked. Perhaps you're passing null values for either token or user to the method. ConcurrentHashMap doesn't allow null for either key or value.

Check the documentation of ConcurrentHashMap#put() method:

Throws:
NullPointerException - if the specified key or value is null

Upvotes: 2

T.J. Crowder
T.J. Crowder

Reputation: 1074198

ConcurrentHashMap doesn't allow either the key or the value to be null, unlike some other Map implementations:

Like Hashtable but unlike HashMap, this class does not allow null to be used as a key or value.

I suspect token or user, not allTokens, is the null in question.

Upvotes: 2

Related Questions