how to make a class as thread safe without synchronization in java and which one is best way.
Asked
Active
Viewed 157 times
-5
-
Make the class final – Krayo Sep 04 '14 at 11:33
-
2You could have no mutable state. Or no state at all. – Thilo Sep 04 '14 at 11:34
-
@Krayo: How does that help? – Thilo Sep 04 '14 at 11:34
-
My mistake! Make it immutable! :) – Krayo Sep 04 '14 at 11:35
-
`class ThreadSafeObject { }` is pretty thread-safe. – David Sep 04 '14 at 11:36
-
Making it immutable is an excellent suggestion; but IMO the safest way ever without any kind of additional programming involved at all is to simply not share the same object instance in multiple threads. – Gimby Sep 04 '14 at 13:42
-
@Krayo,@Thilo,@David - which one is the best way, either synchronization or immutability or something other?(it's my interview question, so please suggest me). – rajesh Sep 06 '14 at 04:57
-
You can't use every situation immutability, but if possible I think it is better (or look at Gimby's comment). – Krayo Sep 06 '14 at 05:55
1 Answers
4
Make the class Immutable. Read more about immutable classes at here Examples of immutable classes
-
which one is the best way, either synchronization or immutability or something other?(it's my interview question, so please suggest me). – rajesh Sep 06 '14 at 04:58
-
Synchronization is needed when to thread need a shared resource that may be changed. And immutability means the resource will never change. So if your Threads share a resource that may or may not be updated or changed you need Synchronization and if the resource will never change or update after creation then it's best to make it immutable. – mirmdasif Sep 06 '14 at 09:28