Hashtable : How can use it with 2/3 different thread?

On android I have one hashtable and two thread which can access to that. - UI thread access to it with containsKey, get and put - other thread access to it with containsKey, get and put and an iterator

I know that hashtable is thread safe, but is sure ?

One thing that I don't understand : why the application doesn't blow up if one thread doesn't see that one value has been removed from the hashtable and the thread iterates on this object ?

How can we define hashtable thread-safe if the iterator isn't ?

EDIT : But now I tell you in more specific way my problem, becasue in other way i'm not clear. Following is reported the code of my concurrentHashMap :

public ConcurrentHashMap<String,Result> Holder = new ConcurrentHashMap<String,Result>(); class Result { public float goal = 0; public float min = 0; public float max = 0; public float seconds = 0; //lastaccess indicate the time of the last access of this Result public float lastaccess = 0; public boolean triggered = false; }

Now one thread B iterates every "x" seconds the Result object and for each key stored in Holder ConcurretHashMap .

Other thread set new Result for a new key or edit the Result for an existing one.

  • I want do the operation of update the Result in atomic way, but the object inside the hashmap scares me.
  • UX thread remove all item from the Holder every x second. To do this operation I to in this way : I created an

    Object mlock = new Object();

in the thread B

syncrhonized(mlock) { //all the thread B function. // Iterate on all of the Holder item }

in the other thread C when it have to call Holder.clear() I have done in this way :

syncronized(mlock) { Holder.clear(); }

  • Is it a correct way to prevent that thread B iterate on a Holder with the inconsistent data ?

-------------Problems Reply------------

It is thread safe but in high concurrent scenarios is recommended to use ConcurrentHashMap as you can see on official documentation

Category:android Views:5 Time:2018-06-27

Related post

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.136 (s). 11 q(s)