Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is this class thread safe?

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

}



}
like image 753
flash Avatar asked Dec 18 '22 01:12

flash


2 Answers

It depends entirely on what state the methods mutate. If they mutate no shared state, they're thread safe. If they mutate only local state, they're thread-safe. If they only call methods that are thread-safe, they're thread-safe.

like image 113
Kent Boogaart Avatar answered Dec 21 '22 09:12

Kent Boogaart


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:

int incrementCount() {
    this.count++;
    // ... Do some other stuff
    return this.count;
}

would not be thread safe. Why is it not? Imagine thread 1 accesses it, count is increased, then some processing occurs. While going through the function, another thread accesses it, increasing count again. 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)

int incrementCount() synchronized {
    this.count++;
    // ... Do some other stuff
    return this.count;
}

The synchronized keyword 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, count goes 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:

int incrementCount(int count) {
    count++;
    // ... Do some other stuff
    return this.count;
}

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.

like image 31
Tarka Avatar answered Dec 21 '22 09:12

Tarka