Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I make all my java code threadsafe?

I was reading some of the concurrency patterns in Brian Goetze's Java Concurrency in Practice and got confused over when is the right time to make the code thread safe.

I normally write code that's meant to run in a single thread so I do not worry too much about thread safety and synchronization etc. However, there always exists a possibility that the same code may be re-used sometime later in a multi-threaded environment.

So my question is, when should one start thinking about thread safety? Should I assume the worst at the onset and always write thread-safe code from the beginning or should I revisit the code and modify for thread safety if such a need arises later ?

Are there some concurrency patterns/anti-patterns that I must always be aware of even while writing single-threaded applications so that my code doesn't break if it's later used in a multi-threaded environment ?

like image 235
Rahul Avatar asked Dec 01 '22 07:12

Rahul


2 Answers

You should think about thread safety when your code will be used in a multithreaded environment. There is no point in tackling the complexity if it will only be run in a singlethreaded environment.

That being said, there are simple things you can do that are good practices anyway and will help with multithreading:

  1. As Josh Bloch says, Favor Immutability. Immutable classes are threadsafe almost by definition;
  2. Only use data members or static variables where required rather than a convenience.
like image 74
cletus Avatar answered Dec 04 '22 01:12

cletus


Making your code thread safe can be as simple as adding a comment that says the class was not designed for concurrent use by multiple threads. So, in that sense: yes, all of your classes should be thread safe.

However, in practice, many, many types are likely to be used by only a single thread, often only referenced as local variables. This can be true even if the program as a whole is multi-threaded. It would be a mistake to make every object safe for multi-threaded access. While the penalty may be small, it is pervasive, and can add up to be a significant, hard-to-fix performance problem.

like image 32
erickson Avatar answered Dec 04 '22 01:12

erickson