开发者

Make thread-safe a normal class with ThreadLocal<T>

I have a normal class designed to be accessed by a single thread and I want to make it thread-safe so many threads can use a single instance at the same time. There are some class level methods and variables which I will make static and using locks make them thread-safe. Also methods which only use local variables are safe (each thread has it's stack) by default.

My question it about proper开发者_如何学Goties of the old class or more generally any non-static variable. Can I simply use ThreadLocal<T> and each thread has it's own set of properties ? Surely I will use locks and other thread-safety issues inside setters (I assume getters are safe).

And is ThreadLocal<T> performance killer ?


Getters are not as safe as you think. The Java memory model gives each thread it's own view of the heap, so if you don't synchronize access to variables then threads may read stale data. Making a variable volatile will prevent stale reads and is fine for primitives, but volatile won't make access atomic.

There are a bunch of classes in the java.util.concurrent package that might help you out. Writing thread-safe code is tricky, so I'd recommend getting a good book on the subject. Brian Goetz's "Java concurrency in practice" is pretty good.


That's not really what thread locals are for. They're intended for cases where each thread will have its own data.

In your case, I would suggest changing the field type to Map<Object, Object> and using Collections.synchronizedMap to to make it thread safe.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜