I'm just a non-developer playing to be a developer, so my question may be extremely simple!
I'm just testing Java multi-threading stuff, this is not real code. I wonder how to make two member variables update at the same time in Java, in case we want them both in sync. As an example:
public class Testing{ private Map<String, Boolean> itemToStatus = new ConcurrentHashMap<>(); private Set<String> items = ConcurrentHashMap.newKeySet(); public static void main(String[] args) { (new Testing()).start("ABC"); } public void start(String name) { if (name.equals("ABC")) { itemToStatus.put(name, true); items.add(name); } }}
In that scenario (imagine multi-threaded, of course) I want to be able to guarantee that any reads of items
and itemToStatus
always return the same.
So, if the code is in the line itemToStatus.put(name, true)
, and other thread asks items.contains(name)
, it will return false. On the other hand, if that other thread asks itemToStatus.containsKey(name);
it will return true. And I don't want that, I want them both to give the same value, if that makes sense?
How can I make those two changes atomic? Would this work?
if (name.equals("ABC")) { synchronised(this) { itemToStatus.put(name, true); items.add(name); }}
Still, I don't see why that would work. I think that's the case where you need a lock or something?
Cheers!