August 22, 2009

WeakHashMap

An Observation
Consider the following code snippet.
1 public class TestWeakHashMap {
2 public static void main(String[] args) {
3 WeakHashMap map=new WeakHashMap();
4 String s1=new String("java");
5 map.put(s1, "good");
6 String s2=new String("java");
7 map.put(s2,"ok");
//Since s1.equals(s2) is true and hash is same, the earlier value against key s1 ("good") in the map is replaced by the new one. ("ok")
8 s1=null;
9 System.gc();
10 System.out.println(map.size());
11 }
12 }
What do we expect the output to be? 1? No thats not correct.
Here s1 and s2 are two different objects on the heap. So in line 5, a new (key,value) pair with key s1 is put into the map. Later when a (key,value) with key s2 is being put into the map, it checks for equals on s1 and s2 and their hashcode. When it finds the equals returns true and hashcde is same, it replaces the value of the earlier entry with the new value. But the issue(?) here is, WeakHashMap/HashMap does not replace the earlier key while adding a (key, value) pair whose key is actually a duplicate key in the map. So even after putting an entry with key s2, the WeakHashMap has only one entry whose key refers to the object refered by s1 and not s2. Now the object on the heap refered by s1, has one strong reference(through s1) and one weak reference through the WeakHashMap. Later when I say s1=null, the object on the heap refered to by s1 lost the strong reference and when gc happens, the entry is removed from the map.
So thats how it works.
Also note WeakHashMap is only a wrapper over HashMap and the HashMap's put api says " If the map previously contained a mapping for this key, the old value is replaced by the specified value."
So just be careful when you use WeakHashMap and your usage scenario is similar to the above.

13 comments:

  1. Ojo con los tips de los ricos, porque no están buscando compañía.
    My web blog Luciana S

    ReplyDelete
  2. Hello, this weekend is good designed for me, since this point in time i am
    reading this fantastic informative article here at my residence.
    Feel free to surf my site :: transfer rumours

    ReplyDelete
  3. Thіs is the гight ωebsite for anybody who would liκе to find out about thіѕ tоpіc.

    You reаlize а wholе lot its almost tοugh to аrgue with yοu (not that I really wіll need tο…HaΗа).
    Үou сeгtаinly put a new spin оn a subjеct
    whіch haѕ been diѕcussed for а long time.
    Excellent stuff, јuѕt excellent!

    Αlso viѕit mу wеb pagе: escorts manhatten
    My webpage ; nyc escorts

    ReplyDelete
  4. These are truly wonderful ideas in regarding blogging. You have touched some
    nice things here. Any way keep up wrinting.


    my site Panic Attacks

    ReplyDelete
  5. Woah! Ι'm really loving the template/theme of this site. It's ѕimple, yet еffective.
    A lot of times it's hard to get that "perfect balance" between usability and visual appearance. I must say you've done a veгy gooԁ јob
    with this. In addition, the blog loads very fast for me on Firеfoх.

    Superb Blog!

    Also visit my ѕite :: arabesk m�rabesk radyo

    ReplyDelete
  6. Greetings! I know this is somewhat off topic but I was wondering if you knew where I could locate a captcha plugin for my comment form?

    I'm using the same blog platform as yours and I'm having problems finding one?
    Thanks a lot!

    Also visit my webpage :: what is kamagra

    ReplyDelete
  7. I'm truly enjoying the design and layout of your blog. It's a very easy on the eyes which makes it
    much more pleasant for me to come here and visit more often.

    Did you hire out a developer to create your theme?
    Fantastic work!

    my web site :: novostar kaufen

    ReplyDelete
  8. great points altogether, you just gained a emblem new reader.
    What may you recommend about your submit that you simply made
    a few days ago? Any certain?

    Feel free to visit my website - erectile dysfunction remedies

    ReplyDelete
  9. Thinking for possible Christmas gifts alone can be so stressful, how considerably more standing all night
    at the malls, when you're patiently waiting for your consider pay in the counter. However, aside in the anticipation and excitement of the upcoming event, you also experience trouble thinking about unique present ideas for your loved ones. Look out to the ones in which you'll be able to engrave names
    (your mother's or of all the loved ones) so that you simply can impart it using a more personalized touch.

    Feel free to visit my blog post http://www.profitbusinessathome.net/

    ReplyDelete
  10. I almost never create responses, but i did some searching and wound up here "WeakHashMap".
    And I do have a couple of questions for you if it's allright. Could it be only me or does it appear like some of these responses look like they are coming from brain dead folks? :-P And, if you are posting on other places, I would like to keep up with anything new you have to post. Would you list of all of your social sites like your Facebook page, twitter feed, or linkedin profile?

    Also visit my website - immobilier castellane 04

    ReplyDelete
  11. A luxury watch isn't just a time piece but something definitely much more than that. The watch is hand-wound and contains three spring barrels offering the 8 days of power. This have to be performed by authorized service professionals.

    Feel free to surf to my web site - watches-bestprice.com ()

    ReplyDelete
  12. these ate excellent information but a bit as well short.


    Also visit my web site Muscle Building weight loss food

    ReplyDelete
  13. Hi there just wanted to give you a quick heads up and
    let you know a few of the pictures aren't loading properly.

    I'm not sure why but I think its a linking
    issue. I've tried it in two different browsers and both show the same outcome.


    Feel free to visit my homepage; telecharger des films
    porno (www.itsjeanish.com)

    ReplyDelete

I'm certainly not an expert, but I'll try my hardest to explain what I do know and research what I don't know.

My Favorite Site's List

#update below script more than 500 posts