You are viewing a plain text version of this content. The canonical link for it is here.
Posted to user@curator.apache.org by Sznajder ForMailingList <bs...@gmail.com> on 2013/10/17 15:36:02 UTC
atomic setCount() in SharedCount
Hi,
In my configuration, several workers update a Sharedcount object by
increment or decrement the counter of the node.
I implemented this by this piece of code:
public void incrementForKey(String key) throws Exception {
SharedCount count = new SharedCount(this.framework,
this.path + "/" + key,0);
count.start();
count.setCount(count.getCount()+1);
}
However, I am worrying about the last line:
count.setCount(count.getCount()+1);
What happens, in case, two workers concurrently, try to increment or
decrement the node value? I suppose this is not atomic and so, how can I
solve that?
Benjamin.
Re: atomic setCount() in SharedCount
Posted by Jordan Zimmerman <jo...@jordanzimmerman.com>.
No, that is not safe. It seems you are wanting to do an Atomic increment. In that case you should use DistributedAtomicInteger instead of SharedCount.
-Jordan
On Oct 17, 2013, at 6:36 AM, Sznajder ForMailingList <bs...@gmail.com> wrote:
> Hi,
>
> In my configuration, several workers update a Sharedcount object by increment or decrement the counter of the node.
> I implemented this by this piece of code:
>
> public void incrementForKey(String key) throws Exception {
> SharedCount count = new SharedCount(this.framework,
> this.path + "/" + key,0);
> count.start();
> count.setCount(count.getCount()+1);
> }
>
> However, I am worrying about the last line:
> count.setCount(count.getCount()+1);
>
> What happens, in case, two workers concurrently, try to increment or decrement the node value? I suppose this is not atomic and so, how can I solve that?
>
> Benjamin.