Re: how to make this code thread safer?
On 7/19/2010 9:33 AM, www wrote:
The code below is completely fine if running on single-thread
environment. But it could break if running on multi-thread environment.
I have added my analysis as comments in the code to show my
understanding why it is not thread safe. My real code, with a pattern
like the code shown here, indeed breaks once in a while with Null
Pointer Exception in multi thread run. Do you think my analysis is
correct? Can you help me on making this code thread safer?
There are a few ways to handle this, the most obvious approach would be
to synchronize the whole thing, which in essences prevents the code from
running in a multi-threaded manor.
I suggest reading the book Java Concurrency in Practice.
<http://www.amazon.com/dp/0321349601?tag=virtuinfinnet-20&camp=14573&creative=327641&linkCode=as1&creativeASIN=0321349601&adid=1Z4QATYV394TGJNXFGXC&>
"This book is a must read for anyone who works in a multi-threaded
application, which turns out is a lot more frequently than you might
expect. If you work in a J2EE container, Swing GUI application, or any
kind of concurrent system, this book will give you the know-how to
create efficient, scalable, and correct programs.
It helps dispel common misconceptions about concurrency, and showcases
the improvements to concurrent programming in Java 5."
--
Daniel Pitts' Tech Blog: <http://virtualinfinity.net/wordpress/>