Java thread synchronization, best compatible utility, read operation

I have a question related to java threads.

To make a very simple example, let's say I have 2 threads.

Topic A Starting an instance of the StockReader class

Thread B starts an instance of the StockAvgDataCollector class

In Thread B, StockAvgDataCollector continuously collects some market data, does some heavy averaging / manipulation, and updates the spAvgData member variable p>

In thread A, StockReader has access to the StockAvgDataCollector instance and its member spAvgData using the getspAvgData () method.

So, Thread A performs the READ operation, and Thread B performs the READ / WRITE operations.

Questions

  • Now, do I need synchronization or atomic functionality or locking, or any concurrency-related stuff in this scenario? It doesn’t matter if Thread A reads an older value.

  • Since Thread A only works READ and does not update anything, and only Thread B performs any WRITE operations, will there be any deadlock scenarios?

I have inserted the paragraph below from the following link. From this paragraph it seems to me that I need to worry about some kind of lock / sync.

http://java.sun.com/developer/technicalArticles/J2SE/concurrency/

Read / write locks

. , , . J2SE 5.0 java.util.concurrent.locks , . ReadWriteLock , . ReadLock() , . writeLock() . , / concurrency . , .

?

java.util.concurrent.atomic?

java.util.concurrent.locks?

java.util.concurrent.ConcurrentLinkedQueue? - StockAvgDataCollector , StockReader . getpAvgData() .

Amit

+5
3

, ReadWriteLock , , , ... , ( , ). .

B, ( ) spAvgData, AtomicDouble ( AtomicReference, , spAvgData).

, :

public class A extends Thread {
  // spAvgData
  private final AtomicDouble spAvgData = new AtomicDouble(someDefaultValue);

  public void run() {
    while (compute) {
     // do intensive work
     // ...
      // done with work, update spAvgData
     spAvgData.set(resultOfComputation);
    }
  }

  public double getSpAvgData() {
    return spAvgData.get();
  }
}
// --------------

public class B {
  public void someMethod() {
    A a = new A();
    // after A being created, spAvgData contains a valid value (at least the default)
    a.start();
    while(read) {
      // loll around
      a.getSpAvgData();
    }
  }
}
+3

, , : spAvgData . spAvgData B A, volatile AtomicReference. , , , . B , , , A .

+3
  • , Thread A ( ), , . , .
  • ReentrantReadWriteLock , , . , .

, StockReader. ReadWriteLock - - , .

(, a volatile), .

+2
source

All Articles