Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 variable, what should I do so each thread updates the variable correctly?

Any help would be greatly appreciated

like image 729
Stephanie Dente Avatar asked Dec 20 '10 21:12

Stephanie Dente


2 Answers

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.

like image 150
Eyal Schneider Avatar answered Oct 15 '22 09:10

Eyal Schneider


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.

like image 25
Serplat Avatar answered Oct 15 '22 08:10

Serplat