Thread safety static variables

旧时模样 提交于 2019-12-25 18:55:29

问题


i read thread safety for static variables and i understand it and i agree with it but

In book java se 7 programmer exam 804 can some one explain to me

public void run() { 
    synchronized(SharedCounter.class) { 
        SharedCounter.count++; 
    }
} 

However, this code is inefficient since it acquires and releases the lock every time just to increment the value of count.

can someone explain to me the above quote


回答1:


The code is not particularly inefficient. It could be slightly more efficient. The main problem is that it is fragile: if any developer forgets to synchronize its access to the global SharedCounter.count variable, you have a thread-safety issue. Indeed, since i++ is not an atomic operation and since changing the value of a variable without synchronization doesn't make the variables new value visible to other threads, Every access to i must be done in a synchronized way.

The synchronization is thus not correctly encapsulated in a single class. Generally, accessing global public fields is bad design. It's even worse in a multi-threaded environment.

Using an AtomicInteger solves the encapsulation problem, and makes it slightly more efficient at the same time.




回答2:


Synchronizing can be expensive, so it shouldn't be used carelessly. There are better ways such as using AtomicInteger.incrementAndGet(); which uses different mechanisms to handle the synchronization.




回答3:


It's inefficient compared to using intrinsic CPU instructions which can do atomic increments without using a lock. See http://en.wikipedia.org/wiki/Fetch-and-add and http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/atomic/AtomicInteger.html



来源:https://stackoverflow.com/questions/25463440/thread-safety-static-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!