0
public class Process extends Thread {

   private static int count=0;

   @Override
   public void run()
   {
       for (int i=0; i< 1000000000; i++)
              count++;
   } }

Consider the above snippet. If more threads of type Process are running, this code is not thread-safe due to the cuncurrent access to the static variable.

How to make this code "thread safe"?

Is it an option to enclose count++ within a static synchronized method and invoking this instead?

Johan
  • 3,561
  • 9
  • 29
  • 45

2 Answers2

4

You better use a builtin synchronized accumulator like AtomicInteger

 AtomicInteger count = new AtomicInteger(0);

 for (int i=0; i< 1000000000; i++)
      count.incrementAndGet();

Another accumulator that comes with Java 8 is the LongAdder which gives a higher throughput under high contention at the expense of more space

 LongAdder longAdder = new LongAdder();

 for (int i=0; i< 1000000000; i++)
    longAdder.increment();

 System.out.println(longAdder.sum()); 

AtomicInteger and locks are great for concurrent access but if parallelism is what you trying to achieve then give LongAccumulator and LongAdders a look, they should scale better on multi-core

Sleiman Jneidi
  • 22,907
  • 14
  • 56
  • 77
2

Use AtomicInteger instead of int, or perform the critical work under synchronization:

private static final Object lock = new Object();

...

synchronized(lock) {
  count++;
}
erickson
  • 265,237
  • 58
  • 395
  • 493