简体   繁体   中英

Should both getter and setter be synchronized?

I have 2 methods with spring @Transactional annotations.

@Transactional(readOnly = true) 
public ConfigParameter getConfigParameter(String key) { 

@Transactional(readOnly = false) 
public void setConfigParameter(ConfigParameter param) {

readOnly = false means that method will by synchronized. When readyOnly = false on setter is set it means access to the setter is synchronized.

Do you agree that in such case, getter should also have readOnly set to true (be synchronized). Because otherwise we will have a risk of getting inconsistent state of returned Object.

I arrived at this problem when I checked this class with FindBugs and got a warning:

Unsynchronized get method, synchronized set method This class contains similarly-named get and set methods where the set method is synchronized and the get method is not. This may result in incorrect behavior at runtime, as callers of the get method will not necessarily see a consistent state for the object. The get method should be made synchronized.

Spring @Transactional semantics and synchronization are two different things entirely - annotating the setter with @Transactional(readOnly = false) will NOT make the method synchronized as if you would declare it as such:

public synchronized void setConfigParameter(ConfigParameter param)

The read-only flag is simply a hit to the underlying persistence engine - the hint MAY be interpreted by the transaction manager to mean that the current transaction is read-only - so nothing to do with how threads will execute the method.

I don't think you're thinking about this properly. Transactional annotations do not belong on these methods.

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