Is a static counter thread safe in multithreaded application?

后端 未结 6 757
青春惊慌失措
青春惊慌失措 2021-01-14 13:02
public class counting
{
  private static int counter = 0;

  public void boolean counterCheck(){
  counter++;
  if(counter==10)
  counter=0;
  }
}

6条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-14 13:39

    first of counter++ by itself is NOT threadsafe

    hardware limitations make it equivalent to

    int tmp = counter;
    tmp=tmp+1;
    counter=tmp;
    

    and what happens when 2 threads are there at the same time? one update is lost that's what

    you can make this thread safe with a atomicInteger and a CAS loop

    private static AtomicInteger counter = new AtomicInteger(0);
    
    public static boolean counterCheck(){
        do{
            int old = counter.get();
            int tmp = old+1;
            if(tmp==10)
                tmp=0;
            }
        }while(!counter.compareAndSet(old,tmp));
    }
    

提交回复
热议问题