|
Java™ by example!
|
|
|
What does it mean for an object or method to be thread-safe?
A thread-safe object means that if several threads access that object simultaneously, that one thread's actions cannot interfere with another's. Threads are run with certain priorities and certain time-slices. A thread can be preempted (interrupted to give another thread control over the CPU) in the middle of its work. An object that is not thread-safe may leave that object in a "corrupted" state. Eg. it may be preempted after writing a row to a database table and before updating a counter variable keeping track of the number of rows. Leaving an object in an inconsistent state may lead to a race condition, a deadlock, or unreliable results. A possible way to prevent this is to synchronize your methods. This ensures that only one thread can have access to a method at a time and must be completed before another one can execute it. It has its performance implications and the whole threading architecture of your application needs to be carefully examined beforehand.
Further Information
Author of answer: Joris Van den Bogaert
Comments to this answer are only viewable by members. Login or become a member!
|
|
|
|
|