07-24-2023, 12:23 PM
Are there overall rules/guidelines for what makes a method thread-safe? I understand that there are probably a million one-off situations, but what about in general? Is it this simple?
1. If a method only accesses local variables, it's thread safe.
Is that it? Does that apply for static methods as well?
One answer, provided by @Cybis, was:
>Local variables cannot be shared among threads because each thread gets its own stack.
Is that the case for static methods as well?
If a method is passed a reference object, does that break thread safety? I have done some research, and there is a lot out there about certain cases, but I was hoping to be able to define, by using just a few rules, guidelines to follow to make sure a method is thread safe.
So, I guess my ultimate question is: "Is there a short list of rules that define a thread-safe method? If so, what are they?"
**EDIT**<br/>
A lot of good points have been made here. I think the real answer to this question is: "There are no simple rules to ensure thread safety." Cool. Fine. But *in general* I think the accepted answer provides a good, short summary. There are always exceptions. So be it. I can live with that.
1. If a method only accesses local variables, it's thread safe.
Is that it? Does that apply for static methods as well?
One answer, provided by @Cybis, was:
>Local variables cannot be shared among threads because each thread gets its own stack.
Is that the case for static methods as well?
If a method is passed a reference object, does that break thread safety? I have done some research, and there is a lot out there about certain cases, but I was hoping to be able to define, by using just a few rules, guidelines to follow to make sure a method is thread safe.
So, I guess my ultimate question is: "Is there a short list of rules that define a thread-safe method? If so, what are they?"
**EDIT**<br/>
A lot of good points have been made here. I think the real answer to this question is: "There are no simple rules to ensure thread safety." Cool. Fine. But *in general* I think the accepted answer provides a good, short summary. There are always exceptions. So be it. I can live with that.