I am writing a class in which I have a List. And I am instantiating the list from the run method of Runnable. As:
public void sendEmailToLegalUsers() {
Log.info("JYM====================================");
try {
new Runnable() {
public void run() {
userCns = new ArrayList<String>();
recipients = new ArrayList<String>();
///other codes
}
};
} catch (Exception e) {
Log.info("Error occurred in LDAPSendMail: "+ e.getMessage());
}
Log.info("END====================================");
}
Now each time the sendEmailToLegalUsers method will be called there will be a new thread. Now I am wondering is the memory scope of the list is bounded to class level (if it is bounded to class level and if say this method is called two times then what will happen of the list which is created by Thread 1 when there is also a Thread 2) or as the threads run in their own scope then the list will have different scope for each thread. Is there any chance to mixup of the list data between two or multiple thread?
If you are using the same
Runnableclass for both of the threads then yes, there will be overlap. If you have a separatenew Runnable()for each of your threads then no, they will be separate list instances but this is only if the lists are defined to be local to theRunnable. If the lists are defined in the calling class then the 2nd time you call your method, theuserCnsandrecipientsfields will be overwritten.In your case, I don’t see any threads being forked at all. All I see is you instantiating the
Runnable. Are you sure you aren’t trying to do something like:In this case, each time you call your
sendEmailToLegalUsers()method, a newRunnablewill be created with new lists.