Answer the question
In order to leave comments, you need to log in
Reordering when posting a link to an UnmodifiableMap?
We have EJB Singleton. In it, after the object is created (but before publication), the rebuild () method is launched, marked with the @PostConstruct annotation. We have a scheduler that runs the same method once a minute. The method initializes the collection, wraps it in an UnmodifiableMap and places it via volatile into the deliverers variable.
We also have a public getDeliverer method that reads data from UnmodifiableMap deliverers in another thread.
@Singleton<br>
@LocalBean<br>
@Startup<br>
@ConcurrencyManagement(ConcurrencyManagementType.BEAN)<br>
public class DeliverersHolderSingleton {<br>
<br>
private volatile Map<String, Deliverer> deliverers;<br>
<br>
@PostConstruct<br>
private void rebuild() {<br>
Map<String, Deliverer> deliverersMod = new HashMap<>();<br>
for (String delivererName : delivererNames) {<br>
/*gettig deliverer by name*/<br>
deliverersMod.put(delivererName, deliverer);<br>
}<br>
deliverers = Collections.unmodifiableMap(deliverersMod);<br>
}<br>
<br>
public Deliverer getDeliverer(String delivererName) {<br>
return deliverers.get(delivererName);<br>
}<br>
<br>
@Schedule(minute="*", hour="*")<br>
public void maintenance() {<br>
rebuild();<br>
}<br>
}<br>
Answer the question
In order to leave comments, you need to log in
Since volatile write and volatile read are in a happens-before relationship, the thread reading the value will see all the actions that the thread that called rebuild() did before volatile write. That is, inside one thread, all operations are in the happens-before relationship, and since this relationship is transitive, other threads will already see the correct value of the variable.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question