lawrence
lawrence

Reputation: 353

thread safe for instance fields

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

Answers (2)

Ravindra babu
Ravindra babu

Reputation: 38910

Key notes:

  1. If your variables are not modified by multiple threads, don't use anything
  2. If your variable reference does not change after creation, use final
  3. If your variable is modified by single thread and accessed by other threads, use volatile
  4. If your variables are modified and accessed by multiple threads: a. Use AtomicXXX if your operations are Atomic - single step transaction b. Use synchronized or Lock API if you have a code block to be guarded

You 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

Krzysztof Krasoń
Krzysztof Krasoń

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

Related Questions