Should you synchronize the run method? Why or why not?

前端 未结 7 1304
温柔的废话
温柔的废话 2020-11-29 07:34

I have always thought that synchronizing the run method in a java class which implements Runnable is redundant. I am trying to figure out why people do this:

相关标签:
7条回答
  • 2020-11-29 08:00

    actually it is really easy to justify "sync or not to sync"

    if your method invocation can mutate the internal state of your object, then "sync" otherwise no need

    simple example

    public class Counter {
    
      private int count = 0; 
    
      public void incr() {
        count++;
      }
    
      public int getCount() {
        return count;
      }
    }
    

    in the example above, incr() needs to be synced, since it will change the val of count, while getCount() synchronization is not necessary

    however there is another corner case, if the count is java.lang.Long, Double, Object then you need to declare as

    private volatile long count = 0;
    

    to make sure the ref update is atomic

    basically that's what you need to think about 99% of time when dealing with multithreading

    0 讨论(0)
提交回复
热议问题