简体   繁体   中英

NullPointerException when attempting ConcurrentHashMap.get()

I have the following code:

public class MyEvent implements org.apache.camel.Processor
{
    static private final Map<Long, String> obj = new ConcurrentHashMap<Long, String>();

    @PostConstruct
    public void postConstruct() 
    {
        for (Object object : cacheList) 
        {
            obj.put(object.getId(), object.getName());
        }
    }

    @Override
    public void process(Exchange exchange) throws Exception 
    {
        synchronized (obj) 
        {
            String value = obj.get(number);
        }
    }
}

Sometimes when starting, I have a NullPointerException in this line:

String value = obj.get(number);

My question is: Why do I get this error and how can I fix it?

Java version 1.6.0_32

Have a look at JavaDocs

Method get will throws NullPointerException if the key is null

I will suggest you to perform null check on number before you will call get

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM