Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NullPointerException when attempting ConcurrentHashMap.get()

Tags:

java

spring

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


1 Answers

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

like image 68
user902383 Avatar answered Aug 31 '26 16:08

user902383



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!