首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

Java Concurrency in Practice reading Notes (一) - Thread Safety

2012-09-08 
Java Concurrency in Practice reading Notes (1) - Thread Safety?volatile?variables, explicit locks,

Java Concurrency in Practice reading Notes (1) - Thread Safety

?

volatile?variables, explicit locks, and atomic variables.

?

?

The machinery of synchronization makes it easy to restore thread safety to the factoring servlet.?Listing 2.6?makes theservice?method?synchronized, so only one thread may enter?service?at a time.?SynchronizedFactorizer?is now thread-safe; however, this approach is fairly extreme, since it inhibits multiple clients from using the factoring servlet simultaneously at allresulting in unacceptably poor responsiveness. This problemwhich is a performance problem, not a thread safety problemis addressed in?Section 2.5.

?

?

}}

?

?

The restructuring of?CachedFactorizer?provides a balance between simplicity (synchronizing the entire method) and concurrency (synchronizing the shortest?possible code paths). Acquiring and releasing a lock has some overhead, so it is undesirable to break down?synchronized?blocks?too?far (such as factoring?++hits?into its own?synchronized?block), even if this would not compromise atomicity.?CachedFactorizer?holds the lock when accessing state variables and for the duration of compound actions, but releases it before executing the potentially long-running factorization operation. This preserves thread safety without unduly affecting concurrency; the code paths in each of thesynchronized?blocks are "short enough".

?


There is frequently a tension between simplicity and performance. When implementing a synchronization policy, resist the temptation to prematurely sacriflce simplicity (potentially compromising safety) for the sake of performance.


Avoid holding locks during lengthy computations or operations at risk of not completing quickly such as network or console I/O.


?

?

热点排行