3

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?

lawrence
  • 353
  • 2
  • 17
  • We don't know the usage of those fields. If they are not used in multi threading context, volatile is not required. If you are not changing the reference, final is not required – Ravindra babu Jul 21 '16 at 08:10
  • TestThreadSafe is used in multi threading context – lawrence Jul 21 '16 at 08:23

2 Answers2

4

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?

Community
  • 1
  • 1
Ravindra babu
  • 37,698
  • 11
  • 250
  • 211
0

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.

Krzysztof Krasoń
  • 26,515
  • 16
  • 89
  • 115
  • confused about instance field variable Modifier, which fields should be declared final,volatile or something else before the instance field variable. how to determine and how to decide, are there some standard to do that? – lawrence Jul 21 '16 at 08:16
  • There is no standard, if there was java would do it for you. You need to look at the code end decide yourself. I personally add final modifiers everywhere and initialize fields in constructors. – Krzysztof Krasoń Jul 21 '16 at 08:19