0

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?

eebbesen
  • 5,070
  • 8
  • 48
  • 70
MRenauld
  • 35
  • 5

5 Answers5

3

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();
}
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
2

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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
2

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

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
0

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.

Teo
  • 3,143
  • 2
  • 29
  • 59
0

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

cigno5.5
  • 703
  • 4
  • 13