5YrsLaterDBA
5YrsLaterDBA

Reputation: 34790

Why ConcurrentHashMap put() return null but the item is put successfully?

I defined a map like this:

private Map<Integer, MyTask> taskMap = new ConcurrentHashMap<Integer, MyTask>();

The call (taskMap is empty then) to put a task will return null and the logger call will throw null pointer exception due to the addedTask.getTaskNameId() call below.

MyTask addedTask = taskMap.put(task.getId(), task);
logger.logTask("added task", "TaskMgmtMgr::registerTask()", "added task=" + addedTask.getTaskNameId());

But I can verify that task was put in successfully with these statements immediately after above logger call:

private String getAvailableTaskListStr()
    {
        Collection<MyTask> tasks = taskMap.values();
        if (tasks.isEmpty())
        {
            return "No running task";
        }
        String nameList = "";
        int index = 0;
        for (MyTask task : tasks)
        {
            if (index == 0)
            {
                nameList += task;
            }
            else
            {
                nameList += ", task";
            }
            index++;
        }
        return "TotalTasks in TaskMap is " + index + ": " + nameList;
    }

I am confused. Anybody can explain this to me? I am using JDK 1.8.0_20.

Upvotes: 1

Views: 1403

Answers (1)

NFE
NFE

Reputation: 1187

Map returns previous associate value. if there is no value associate previously than it will return null. that is why you are getting null.

the previous value associated with key, or null if there was no mapping for key

just example:

Map<Integer, String> taskMap = new ConcurrentHashMap<Integer, String>();
        String hello=taskMap.put(34, "Test1");
        System.out.println("hello "+hello);//It returns null
        hello=taskMap.put(34, "Test2");
        System.out.println("hello "+hello);//it returns Test1

Output:

hello null
hello Test1

Upvotes: 8

Related Questions