So, in order to avoid any NullPointerExceptions being thrown we need have a check for nulls being returned before making any calls on returned object. See snippet below to understand it further :-
Iterator
while(it.hasNext()) {
String key= (String)it.next();
String value= testConcHashMap.get(key);
//value.equals("anotherstring");//May throw a Null Pointer
if(! (value== null)){ //check for null
value.equals("anotherstring");
}
}
For further reading see java docs : http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/ConcurrentHashMap.html
To avoid NullPointerException, you should instead iterate over the values:
ReplyDeleteIterator it = testConcHashMap.values().iterator();
while(it.hasNext()) {
String value = (String)it.next();
David, so you meant that while iterating over the concurrent hahmaps we should always iterate over values?And above code will never throw unexpected Null pointers.Please elaborate.
ReplyDeleteThe code which I stated will always avoid unexpected null pointers.
I got your point, but don't you think so much the concurrenthashmap can do and the user should also worry a bit about concurrency than just putting a "null" check.
ReplyDeletethis is really worth...
ReplyDeletewrote a small article around why CHMs cant have null values (http://anshuiitk.blogspot.com/2010/12/why-concurrenthashmap-does-not-support.html) .. can you said you could get a NPE ... so instead use putIfAbsent method. Read Derek's blog regarding this at http://dmy999.com/article/34/correct-use-of-concurrenthashmap . Let me know on my blog site in case of doubts ..
ReplyDeleteInteresting post, ConcurrentHashMap provides better throughput and speed by locking a portion of Map but as Apurv pointed out that could lead to null pointer exception.
ReplyDeleteThanks
Javin
Why String is immutable in Java
to avoid NullPointerException, use following
ReplyDelete"anotherstring".equals(value);
My bгοtheг recоmmеnԁеd I wοuld
ReplyDeleteposѕibly lіkе this ωеb sіte.
He was onсe totally right. This submit truly made
my day. You can not сonsіdeг simрly hоω а lot time I haԁ spent for thіs
info! Τhаnκѕ!
My web site sim free mobile
Hey there! I simply ωant to offer you а big thumbs up for the gгeаt info you have got here on this post.
ReplyDeleteI wіll be coming back to your website for mоre soon.
Also visit my blog doesn't