I am having a code like below in my class that will act like my ‘Task’ class. i will create multiple instances of this class and pass it to the threadpool
class Task {
public void doJob() {
String s = informationDto.getName();
}
}
DTO:
class InformationDto{
private String name;
public getName(){}
public setName(String n){}
}
i am wondering about the informationDto.getName(); statement. will it be return me the correct name always in a multithreaded environment?
what happens if the getName() method is static?
i want to use informationDto each for every Task class i am creating. what will be the best way to do this?
1) i want to keep one InformationDto for each Task class.
2) since instance variables are not thread safe i am wondering if i access getName() method (since name is a instance variable ) would i get the correct name that i set in the Task class?
3) it is like if i use a util class inside the Task class will it be thread safe? if not how can i use kind of util instance in a thread safe manner?
I am still not exactly clear about your problem but enough said in comments, will try to give you an answer.
I would assume the
getName()does this:and
setName()does this:where
nameis:Having an instance of this class used by multiple threads does not guarantee that everyone will see the same thing when they ask
getName(), not until it’s guaranteed that no one callssetName()on it while the others are working.One way to guarantee the
getName()to return a consistent and the same value is to lock it down. You do so by making your object immutable:This way
nameis guaranteed not to change and you can pass your object safely to as many threads as you wants knowing that no one can change it. This will however make it not a perfect POJO in a way that you can’t set that property. If you need to be able to usesetName()(directly or indirectly through some kind of a framework) this won’t do it for you.What else can go wrong with this instance in a multithreaded environment? not much. The
getName()won’t return a partial state, like half the old value and half the new value being written by another thread. You’re safe there. Making thegetName()static doesn’t change much. It will now be a class method, not an instance method with thenamealso becomingstaticwhich is very much a global state tat you don’t want in your backyard.Hope this answers your question or at least gives you enough clues to figure out your next steps.
UPDATE. Like it was pointed out in comments, if you do expect the
nameto change and want to be sure all threads read the most recent value, you can usevolatilewhen declaring the member variable:Using
volatilewill ensure your threads “communicate” on modification events and don’t trust their local caches.