开发者

if multiple threads are updating the same variable, what should be done so each thread updates the variable correctly?

If multiple threads are updating the same varia开发者_运维技巧ble, what should I do so each thread updates the variable correctly?

Any help would be greatly appreciated


There are several options:

1) Using no synchronization at all

This can only work if the data is of primitive type (not long/double), and you don't care about reading stale values (which is unlikely)

2) Declaring the field as volatile

This will guarantee that stale values are never read. It also works fine for objects (assuming the objects aren't changed after creation), because of the happens-before guarantees of volatile variables (See "Java Memory Model").

3) Using java.util.concurrent.AtomicLong, AtomicInteger etc

They are all thread safe, and support special operations like atomic incrementation and atomic compare-and-set operations.

4) Protecting reads and writes with the same lock

This approach provides mutual exclusion, which allows defining a large atomic operation, where multiple data members are manipulated as a single operation.


This is a major problem with multi-threaded applications, and spans more than I could really cover in an answer, so I'll point you to some resources.

http://download.oracle.com/javase/tutorial/essential/concurrency/sync.html

http://www.vogella.de/articles/JavaConcurrency/article.html#concurrencyjava_synchronized

Essentially, you use the synchronized keyword to place a lock around a variable. This makes sure that the piece of code is only being run once at a time. You can also place locks around the same object in multiple areas.

Additionally, you need to look out for several pitfalls, such as Deadlock.

http://tutorials.jenkov.com/java-concurrency/deadlock.html

Errors caused by misuse of locks are often very difficult to debug and track down, because they aren't very consistent. So, you always need to be careful that you put all of your locks in the correct location.


You should implement locking on the variable in question. Eg.

http://download.oracle.com/javase/tutorial/essential/concurrency/newlocks.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜