Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are private variables thread safe

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;
    }
}
like image 406
Vicky Avatar asked Nov 26 '22 04:11

Vicky


1 Answers

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.

like image 87
ayyoob imani Avatar answered Mar 15 '23 19:03

ayyoob imani