I am working to solve interesting concurrent problem! Not sure if I understand it correctly since I am little bit confused.
The system needs to process the prices, and typically they cannot be processed as quickly as they arrive, so the implementation must sample the latest price. The external system produces prices for several entities, interleaved into a single sequence of the form:
EntityA: pa1, pa2, pa3... EntityB: pb1, pb2, pb3 ... Time ▶ ▶ ▶For example, if during the time taken to process pricepa1
the pricespa2
,pa3
, andpa4
arrive, the next price the application should process ispa4
and all previous prices should be ignored. Prices for other entities (e.g.pb1
) do not affect the latest price entity fora
, but are processed independently in the same way with respect to entityb
.
For thread-safety I wanted to use ConcurrentMap
ConcurrentHashMap<String, BigDecimal> concurrentHashMap = new ConcurrentHashMap<String, BigDecimal>();
public BigDecimal getPrice(String id){
return concurrentHashMap.get(id);
}
public void updatePrice(String id, BigDecimal newPrice){
concurrentHashMap.put(id, newPrice);
}
- Will it guarantee a thread safe read/write?
- If I write to key
"a"
will it lock the whole Map or writes to"b"
key is available? - What does take following part of the task means? If during the time taken to process price Pa1 the prices Pa2, Pa3, and Pa4 arrive, then the next price the application should process is Pa4 and all previous prices should be ignored. - Probably I am overcomplicating things but does that mean I should not store and cancel price update if new more recent price arrive? If yes, then how would implementation look like?
ConcurrentHashMap
are not synchronized (see javadoc), only modification/update operations are. And lock occur only on segment, if 2 threads are modifying 2 differents keys: that's ok, they don't need to be synchronized.