Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I analyze Java source code and ensure it is Thread safe

I am reading through java codes to ensure it is thread safe.

As I understand, any local variables within the method is thread safe since it belongs to the stack memory address. Any class / instance variables is not thread safe as it belongs to the heap memory is shared by other thread.

By rule of thumb, I can put a synchronized keyword on every method which touches the class variables.

Is there any eclipse plugin, or rules I can analyze / prevent multi-threading issues?

like image 487
ilovetolearn Avatar asked Mar 31 '13 15:03

ilovetolearn


2 Answers

Threading world is one of the most touchy thing for a good programmer. Every solution to thread issues requires a big knowledge of the context. Any plugins would not be enough "intelligent" to choose the most relevant solution everytime.

Indeed, synchronized represents about 5% of every possible solutions. Think to concurrent collections, ConcurrentHashMap for example which is very well thought and doesn't use a basic big locking on it => more more studied complex than that.

Think to volatile, to perform ensure barrier memory while avoiding any kind of atomocity through any locks; atomicity is not its role, but in some cases, this would be great to avoid it to improve performance.

Therefore, forget any plugins (even if some may exist) for thread-safety but trust your brain ;)

Note: Putting synchronized keyword on each writing class, would be.........ugly without talking about the poor performance...

like image 171
Mik378 Avatar answered Oct 15 '22 11:10

Mik378


I don't think there is anything that will definitively check for thread safety, there are some tools that have already been mentioned, like findbugs that will do a reasonable job of finding the obvious mistakes.

It is very much up to the programmer to ensure that their program is not leaking variables or references into different threads and where things are used in multiple threads ensuring that each thread see's the 'correct' value.

Design for safety before performance, you might find that it performs fine for your needs but if you put optimisation in you increase complexity and potentially failure, it might not end up being the bottleneck.

I would recommend reading reading specifically Java Concurrency In Practice, you may also find Effective Java helpful as well.

like image 41
Alex Edwards Avatar answered Oct 15 '22 11:10

Alex Edwards