3

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

RealSkeptic
  • 33,993
  • 7
  • 53
  • 79
  • 3
    Where do you define number? ConcurrentHashMap get method could throw NPE if key is null. – mkrakhin Feb 10 '15 at 14:59
  • 4
    what is `number` parameter there? – Marcin Szymczak Feb 10 '15 at 14:59
  • possible duplicate of [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it) – khelwood Feb 10 '15 at 15:02
  • 1
    Where is `number` defined? Also, I think you need a static initializer for your map if you want to make it final. [This question](http://stackoverflow.com/questions/507602/how-can-i-initialize-a-static-map) might be helpful – mstbaum Feb 10 '15 at 15:02
  • 1
    As a side note: Java 1.6 is no longer supported. You should upgrade. – RealSkeptic Feb 10 '15 at 15:11
  • i cannot do a static initialization, because of other limitations. –  Feb 10 '15 at 15:11
  • 1
    You still haven't edited your question to show us where `number` is defined and set, or explained what it is used for. When you do that, you can also explain why you can't initialize it. – RealSkeptic Feb 10 '15 at 15:12
  • "number" is inited from other objects, so indeed this could be the problem, i wrote below also the stacktrace i get. –  Feb 10 '15 at 15:22
  • by the way, you shouldn't be synchronizing on the collection as a lock `synchronized (obj)` that's totally wrong. – ACV Sep 27 '18 at 10:27

1 Answers1

13

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

user902383
  • 8,420
  • 8
  • 43
  • 63
  • i think the problem indeed can be in "number". because i have the following stacktrace: **CaughtExceptionType:java.lang.NullPointerException, CaughtExceptionMessage:null, StackTrace:java.lang.NullPointerException at java.util.concurrent.ConcurrentHashMap.get(ConcurrentHashMap.java:917) at MyEvent.process(MyEvent.java:61)** where 61 is the line i mentioned. I will check and if something i will come with an update. –  Feb 10 '15 at 15:05