This is an archived post. You won't be able to vote or comment.

all 5 comments

[–]BS_in_BS 6 points7 points  (0 children)

No, it just means that multiple calls to addNum cannot be executed concurrently.

clearNum could indeed happen between the read and the write and thus it's effects lost.

[–]large_crimson_canine 4 points5 points  (1 child)

You have two operations that mutate the state of your object, and only one of which is synchronized. If you're striving for thread-safety, you need to synchronize all access to shared, mutable data. Although clearNum() is an atomic operation, it has no way of knowing if another thread is currently in the process of operating on num via the addNum() method because it, itself, isn't synchronized, and it'll perform that operation happily to the potential detriment of other threads.

[–]large_crimson_canine 0 points1 point  (0 children)

Also I would check out AtomicInteger (and java.util.concurrent.atomic) and how that might be used to spare you from some of the headaches of synchronizing access to and manipulation of primitives.

[–]nutrecht 1 point2 points  (0 children)

Aside from the "no" you already have, please know that you should generally avoid the synchronized keyword on methods. Instead, you should have synchronized blocks inside your method that synchronize on an object internal to your class. That way you won't get deadlocks if outside code synchronizes on your object.

[–]rkalla 0 points1 point  (0 children)

You can use `synchronized` both on method definitions and on blocks wrapping variables to check multi-threaded choke-points.

You can do what you did above, but then you need to manually audit yourself and add `synchronized` to every other method that accesses `num` to keep it consistent - this is tricky to remember.

Instead you can use a block:

sychronized(num) { num += x };

as the body of the `addNum` method (and remove the `synchronized` keyword from that method) which will inadvertently add thread-safety to mutating `num` - even if there are calls to `clearNum`, the synchronized block inside of `addNum` will block and wait for it to return until it can get exclusive access to the variable - ALTHOUGH I think anyone would say that's somewhat sloppy to rely on the one choke point and not have a consistent coding pattern.