I have a static Map
private static Map<String, Car> cars = new HashMap<~>() //Map holding car objects
I use the variable inside a method like
private static String getCar(String name){
return cars.get(name);
}
So, if I want to put lock on cars, is it fine to do like below for thread safety.
private static void xyz() {
synchronized(cars) {
Car c = getCar("abc");
c.setColor("Green");
}
}
Any Suggestions?
Java’s
synchronizedkeyword can be applied to any object to “acquire a lock” on that object (or “synchronize on” that object) before proceeding. If any other process tries to run code that synchronizes on the same object at the same time, it will block until the process that locked the object exits the synchronized block.The object you synchronize on does not have to be actually used in any part of the
synchronizedblock; it could be a simple mutex object whose only purpose is to be locked and unlocked in synchronized blocks. However, it is important to note that simply synchronizing on an object does not prevent other threads from modifying it if they do not also synchronize on that object. It is a programmer/convention-enforced lock rather than a built-in lock, and all of your code that uses a shared object must “agree” to synchronize on it.For example, with the code you wrote above, even though your
xyz()method synchronizes oncars, you could write another method like this:that modifies
carswithout callingsynchronized. It would be possible for this method to modify the “abc” car at the same time as your methodxyz()is modifying it (i.e. violate thread safety) because it does not contain any code that invokessynchronizedoncars.If you want to ensure that your
carsmap is thread-safe (i.e. never modified by two methods concurrently), you must eithercarsfirst callssynchronized(cars)