简体   繁体   English

尝试 ConcurrentHashMap.get() 时出现 NullPointerException

[英]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:有时在启动时,我在这一行中有一个NullPointerException

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 Java 版本 1.6.0_32

Have a look at JavaDocs看看JavaDocs

Method get will throws NullPointerException if the key is null如果键为空,方法 get 将抛出NullPointerException

I will suggest you to perform null check on number before you will call get我会建议您在拨打 get 之前对number进行空检查

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ConcurrentHashMap.get() 迭代器 - ConcurrentHashMap.get() Iterator ConcurrentHashMap.get() 如何防止脏读? - How does ConcurrentHashMap.get() prevent dirty read? ConcurrentHashMap.get()是否保证通过不同的线程看到以前的ConcurrentHashMap.put()? - Is ConcurrentHashMap.get() guaranteed to see a previous ConcurrentHashMap.put() by different thread? 尝试从SQLite数据库获取数据时发生NullPointerException / CursorOutOfBoundsException - NullPointerException / CursorOutOfBoundsException when attempting to get data from SQLite db DefaultKafkaConsumerFactory - ConcurrentHashMap - NullPointerException - DefaultKafkaConsumerFactory - ConcurrentHashMap - NullPointerException 尝试访问对象数组时发生NullPointerException - NullPointerException when attempting to access array of objects 尝试访问数据库时导致NullPointerException - NullPointerException resulting when attempting to access database ConcurrentHashMap putIfAbsent:当跟随get()调用时的原子性 - ConcurrentHashMap putIfAbsent : atomicity when followed by a get() call 尝试启动JWS应用程序时发生NullPointerException - NullPointerException when attempting to start JWS application 尝试在Text对象上使用.setText时发生NullPointerException - NullPointerException when attempting to use .setText on a Text object
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM