Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 378
lawrence Avatar asked Jul 28 '26 11:07

lawrence


1 Answers

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?

like image 163
Ravindra babu Avatar answered Jul 30 '26 00:07

Ravindra babu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!