Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When do you have to worry about thread safety?

What are some situations where you need to worry about whether a static method is thread safe?

For example, if I have static utility function that doesn't touch any static class level variables, is that method already thread safe? If I have a static method that does touch static class variables, is that method potentially not thread safe?

Thanks in advance.

like image 816
Brian DiCasa Avatar asked Dec 14 '10 22:12

Brian DiCasa


People also ask

How do you know if something is thread-safe?

A method will be thread safe if it uses the synchronized keyword in its declaration.

What is considered thread-safe?

In computer programming, thread-safe describes a program portion or routine that can be called from multiple programming threads without unwanted interaction between the threads. (A thread is an instance of the program running on behalf of some user or process.)

When should you not use threads?

The one reason to not use multi-threading is: There is one task, and no user interface with which the task will interfere.


1 Answers

If I have static utility function that doesn't touch any static class level variables, is that method already thread safe?

Most of the time - what matters is if your method is reentrant. Something like this is reentrant because everything is local variables and each thread receives its own copy:

static int add(int a, int b)
{
    return a + b;
}

There are still some things to be careful of. If you pass in an object to the method and the method mutates the object and before the method completes you call the same method again on a different thread but with the same object, then you have a problem.

If I have a static method that does touch static class variables, is that method potentially not thread safe?

The main issue again is if the variables are mutable. If you are only reading from immutable objects then there may not be any problem.

If you call a method and you are not sure if it is reentrant and the documentation doesn't say, it's best to assume that it isn't.

like image 95
Mark Byers Avatar answered Sep 21 '22 12:09

Mark Byers