• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to add Map in a ThreadLocal?

 
Joemon Anthony
Greenhorn
Posts: 26
Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I want to add a Map in a ThreadLocal.

I tried like this:


And in the main class :

But after executing this I am getting null pointer exception.

Could any please help.
 
Paul Cowan
Greenhorn
Posts: 9
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The typical pattern for ThreadLocal is to use an anonymous inner class which overrides initialValue(), like this:

 
Joemon Anthony
Greenhorn
Posts: 26
Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Paul.

It worked with your solution.
 
Chan Ag
Rancher
Posts: 1089
14
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes the first call to the get method of the ThreadLocal invokes the initialValue method to get the initial value of the ThreadLocal variable for that thread unless you have set the initial value by calling the ThreadLocal's set method explicitly. If the initialValue method is not overridden, the get method call will return null if the call to get method resulted in a call to the initialValue method.

You might like to read the whole of this page where it is explained quite well.



 
Joemon Anthony
Greenhorn
Posts: 26
Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Chan.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!