Logical comparison between Java synchronized keyword and spring @ transactional annotation

In one of the demonstrations on spring / Hibernate transactions, I made an opinion that @ transactional has many logical similarities to synchronize keywords on methods Sure enough, they are completely different beasts, but they are all applied to methods as methods, and access to certain resources is controlled through some kind of shared monitor (for example, recorded in DB)

Several people in the crowd immediately objected and claimed that my comparison was wrong I don't remember specific arguments, but I can also see some views here For example, starting from the beginning and transaction, the synchronization of the whole method will take effect only when the statement accessing DB is reached Plus synchronized does not provide any read / write locking mode

So the question is, my comparison is completely wrong. I should never use it, or if it makes sense to present it to experienced engineers in appropriate wording. Do they know how synchronization works but try to understand AOP transactions? What should this wording be?

A little update

Obviously, my question sounds like comparing database transactions with entering synchronized methods in Java This is not the case My idea is to compare the semantic similarity between @ transactional and synchronized

One of the reasons why I put forward it is also to illustrate communication behavior For example, if @ transactional is promotion_ Required, which will have many similarities to the input synchronized block For transactions: if the transaction exists, we just continue to use it. If not, we will create one For synchronization, if we already have a monitor, we continue it, if not, we will try to get it Of course, for @ transactional, we don't lock method boundaries

Solution

If we think of @ transactional as a means of locking database resources (because it is used in transactions) – then the comparison makes some sense

However, this is what they have in common Synchronized is defined on the object monitor (and only protects it), which is known when using keywords, and transactions can lock multiple resources (not known at the beginning of the transaction), or they may not lock any resources at all (optimistic locking, read-only transactions)

So ultimately – don't use this comparison, they have a lot of differences, not in common

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>