This discussion is archived
1 2 Previous Next 17 Replies Latest reply: Nov 2, 2012 4:05 PM by EJP Go to original post RSS
  • 15. Re: Is this method Thread safe?
    LosLobo Newbie
    Currently Being Moderated
    I'm assuming everyone passing in a hashmap has their own copy which is not shared.
    My question is if two threads pass in different HashMaps say one with 1 null and another with 10 nulls, is it possible they could step on each other inside the method itself and one of them to not get the correct count back. So hypothetically, if a million threads called this method at the same instance each having a different expected return value is it possible that one of them could receive an improper return value because the method is looking at someone elses hashmap and returning it's count of null values? If this was NOT static and an instance method I would expect it to return the correct count every time since each of the million instances has it's own sandbox it's running in. Thoughts?

    public static int countNonNullEntries(HashMap hm){
    if(hm==null)return 0;
    int count=0;
    for(int i=0; i<hm.size(); i++) {
    if(hm.get(i)!=null)
    { count++;}
    }
    return count;
    }
  • 16. Re: Is this method Thread safe?
    DrClap Expert
    Currently Being Moderated
    Perhaps you should start by explaining why you think that "each... instance... has it's own sandbox" and why you think that it makes a difference whether the method is static or not. You really can't understand multiprocessing without knowing the programming language properly in the first place. Otherwise people are just wasting their time trying to map normal terminology onto your flawed understanding.
  • 17. Re: Is this method Thread safe?
    EJP Guru
    Currently Being Moderated
    is it possible that one of them could receive an improper return value because the method is looking at someone else's hashmap and returning it's count of null values?
    No. But that 'thread safety' comes entirely from how you use the method. It isn't a property of the method itself. The method itself is not thread-safe.
    each of the million instances has it's own sandbox it's running in.
    Please stick to the standard terminology. 'Sandbox' already has a meaning in Java, and that isn't it. Each thread has its own stack; parameters and local variables are pushed onto the stack; ergo each thread's invocation of the method has its own parameters and local variables. If you can also ensure that each thread has its own hash map for passing to this method, then the totality of all this is thread safe. Not otherwise.
1 2 Previous Next

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points