Thursday, June 16, 2005

jGuru: What is the meaning of calling a method or object thread-safe?

jGuru: What is the meaning of calling a method or object thread-safe?: "Answer
Basically, calling a method 'thread-safe' means that even if multiple threads try to access it simultaneously, nothing bad happens. Here 'bad' usually means that due to race conditions, or deadlock, or other pitfalls, the object's state gets corrupted, or its methods produce unreliable results. A method usually acheives thread-safety by protecting access to shared resources. This usually translates to using the Java synchronized keyword to protect blocks of code that access instance variables, or other shared variables.

For an object to be thread-safe, it must be possible for multiple threads to simultaneously access the same method, or multiple methods, in that object. Usually this is acheived by assuring that each method is thread-safe, but this doesn't always suffice, since methods can call each other in strange ways, leading to deadlock and other weirdness.

It is very difficult to prove that an object is thread-safe. The main rule of thumb for making thread-safe objects is, 'Make all the instance variables private, and all the public accessor methods synchronized.' However, this is sometimes difficult to achieve in practice, due to exigencies of performance, architecture, or implementation.

Accurate multithreaded programming is a true art, and very difficult to master. Read 'Java Threads' by Oaks and Wong, and 'Concurrent Programming in Java' by Lea, for inspiration in your quest to become a thread-safe programmer. "

No comments: