Spring -- conflict between annotation and synchronized

Keywords: Spring

Spring's annotation of things will cause synchronization lock to fail. The reason is that the priority of annotation of things is higher than that of synchronized. Synchronization lock is executed after opening things, which will cause other threads to request that things have not yet submitted to read data and will not be updated.

Solution: add synchronization lock before opening things. There are two ways.

One is to add synchronization lock to the Controller method and annotation to the Service implementation method

One is to manually lock and control things in the Service implementation method, which is described as follows:

 

@Service
public class OrderServiceImpl extends BaseServlet implements OrderService {
    private static Logger logger = Logger.getLogger(OrderServiceImpl.class);
    private Lock orderLock = new ReentrantLock(); // Create lock

    @Resource(name = "transactionManager")
    private DataSourceTransactionManager transactionManager;    // Initialize control of things
    private DefaultTransactionDefinition def = new DefaultTransactionDefinition();


    @Override
    public Map<String, Object> userNewOrder(Integer userId, int priceType, Order order, int isFollow) {
        Map<String, Object> resultMap = Maps.newHashMap();
        
        orderLock.lock();   // Lock up

        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); // Object isolation level, open new transaction
        TransactionStatus status = transactionManager.getTransaction(def); // Get transaction status

        try {
            // Related business processing---
            transactionManager.commit(status);  // Things submitted manually
            resultMap.put("order", order);

        } catch (Exception e) {
            logger.error("========[ New order exception ]:", e);
            transactionManager.rollback(status);    // Things rolling back manually
            return AllStateEnum.resultMap(ERRORREQUEST);
        } finally {
            orderLock.unlock(); // Release lock
        }

        return resultMap;
    }
}

Posted by superdezign on Thu, 02 Apr 2020 05:17:55 -0700