简体   繁体   中英

Why synchronize on small objects?

How does synchronization block in Java performance depends on object size on which synchronization is being performed?

synchorized (lock) {
    //some code here
}

Imagine lock could be just new Object() as it is used to be or it could be instance of immutable class but with a huge number of fields initialized.

synchronized是不受对象大小影响的对象,因为它是对象上的(小)信号量,性能问题与多个线程如何访问对象有关,换句话说,与应用程序的结构有关。

The synchronization's performance does not depend on the size of the object you're synchronizing on. However, using a "large" object for synchronization may hurt performance in other areas - first, it may take time to initialize it, and second, it will hog memory, causing more page-faults etc. (assuming it's not required by your code regardless, in which case it makes no sense to hold an additional object just for synchronization purposes).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM