Reputation: 353
when programming for a thread safe project, how to determine which field should be thread safe. for example we have a class in a project called TestThreadSafe in a multithread project.
public class TestThreadSafe {
public AtomicLong pCounter = new AtomicLong();
public AtomicLong mCounter = new AtomicLong();
protected final ConcurrentMap<K, V> Map = new ConcurrentHashMap<K, V>();
private ScheduledExecutorService ses;
private String dir;
}
Here, why do not define ses and dir as final or volatile fields?
Upvotes: 3
Views: 3814
Reputation: 38910
Key notes:
final
volatile
AtomicXXX
if your operations are Atomic - single step transaction
b. Use synchronized
or Lock API if you have a code block to be guardedYou can find more details about high level concurrency constructs here
Related SE questions:
What is the difference between atomic / volatile / synchronized?
What is meant by "thread-safe" code?
Upvotes: 4
Reputation: 27476
It is always good to mark a field as final
(you don't loose any performance, but gain compile time checks and threading related bonus - field will always have given value, not the default one).
As for volatile
- it makes CPU optimizations (caches) go away so using such field will be slower.
volatile
should be used if you share given field value between threads - where one thread is writing data to it and multiple (>= 1) threads read from it.
Upvotes: 0