in the code we have:
public static volatile List<Person> allPeople = new ArrayList<>();
and we have to add synchronized(allPeople) to the each case:
case "-c":
synchronized (allPeople) {
for (int i = 1; i < args.length; i = i + 3) {
create(args[i], args[i + 1], args[i + 2]);
}
}
break;
questions is what does the synchronized add to volatile?
The allPeople list is volatile what does the synchronized(allPeople) add to this?
Resolved
Comments (2)
- Popular
- New
- Old
You must be signed in to leave a comment
Guadalupe Gagnon
28 December 2020, 18:22solution
http://tutorials.jenkov.com/java-concurrency/volatile.html
Read this. Specifically the part "volatile is Not Always Enough" would answer your question.
+2
Liliane Top Backend Developer at Procura
28 December 2020, 18:57
found it
When is volatile Enough?
As I have mentioned earlier, if two threads are both reading and writing to a shared variable, then using the volatile keyword for that is not enough. You need to use a synchronized in that case to guarantee that the reading and writing of the variable is atomic. Reading or writing a volatile variable does not block threads reading or writing. For this to happen you must use the synchronized keyword around critical sections.
+1