Does a developer who is developing an api (like Collections api in java) should manually throw ConcurrentModificationException when two threads try to modify the object's data?
Why does this piece of code not throw an exception as multiple threads try to modify the content of the Person
's object?
public class Main {
public static void main(String[] args) {
// write your code here
RunnableDemo r = new RunnableDemo();
for (int i = 0; i < 10; i++) {
Thread t = new Thread(r, "Thread " + i);
t.start();
}
}
}
class RunnableDemo implements Runnable {
private Person person = new Person();
@Override
public void run() {
for (int i = 0; i < 100; i++) {
person.setName("Person" + i);
System.out.println(person.getName());
}
}
}
class Person {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
You should throw an exception when you think that you have to. your code does not throw an exception when two threads try to modify the person object concurrently but you may get unpredictable results in such a situation and you should prevent concurrent modification manually.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With