consider this class,with no instance variables and only methods which are non-synchronous can we infer from this info that this class in Thread-safe?
public class test{
public void test1{
// do something
}
public void test2{
// do something
}
public void test3{
// do something
}
}
Not being thread safe means that if multiple threads try to access the object at the same time, something might change from one access to the next, and cause issues. Consider the following:
would not be thread safe. Why is it not? Imagine thread 1 accesses it,
countis increased, then some processing occurs. While going through the function, another thread accesses it, increasingcountagain. The first thread, which had it go from, say, 1 to 2, would now have it go from 1 to 3 when it returns. Thread 2 would see it go from 1 to 3 as well, so what happened to 2?In this case, you would want something like this (keeping in mind that this isn’t any language-specific code, but closest to Java, one of only 2 I’ve done threading in)
The
synchronizedkeyword here would make sure that as long as one thread is accessing it, no other threads could. This would mean that thread 1 hits it,countgoes from 1 to 2, as expected. Thread 2 hits it while 1 is processing, it has to wait until thread 1 is done. When it’s done, thread 1 gets a return of 2, then thread 2 goes throguh, and gets the expected 3.Now, an example, similar to what you have there, that would be entirely thread-safe, no matter what:
As the only variables being touched here are fully local to the function, there is no case where two threads accessing it at the same time could try working with data changed from the other. This would make it thread safe.
So, to answer the question, assuming that the functions don’t modify anything outside of the specific called function, then yes, the class could be deemed to be thread-safe.