javascript
关于Spring的事务Transactional,锁同步,并发线程
Spring事務(wù)傳播機(jī)制和數(shù)據(jù)庫(kù)隔離級(jí)別
在標(biāo)準(zhǔn)SQL規(guī)范中定義了4個(gè)事務(wù)隔離級(jí)別,不同隔離級(jí)別對(duì)事務(wù)處理不同 。
未授權(quán)讀取(Read Uncommitted): 也稱 未提交讀。允許臟讀取但不允許更新丟失,如果一個(gè)事務(wù)已經(jīng)開(kāi)始寫數(shù)據(jù)則另外一個(gè)數(shù)據(jù)則不允許同時(shí)進(jìn)行寫操作但允許其他事務(wù)讀此行數(shù)據(jù)。該隔離級(jí)別可以通過(guò) “排他寫鎖”實(shí)現(xiàn)。事務(wù)隔離的最低級(jí)別,僅可保證不讀取物理?yè)p壞的數(shù)據(jù)。與READ COMMITTED 隔離級(jí)相反,它允許讀取已經(jīng)被其它用戶修改但尚未提交確定的數(shù)據(jù)。
授權(quán)讀取(Read Committed): 也稱提交 讀。允許不可重復(fù)讀取但不允許臟讀取。這可以通過(guò)“瞬間共享讀鎖”和“排他寫鎖”實(shí)現(xiàn),讀取數(shù)據(jù)的事務(wù)允許其他事務(wù)繼續(xù)訪問(wèn)該行數(shù)據(jù),但是未提交寫事務(wù)將 會(huì)禁止其他事務(wù)訪問(wèn)該行。SQL Server 默認(rèn)的級(jí)別。在此隔離級(jí)下,SELECT 命令不會(huì)返回尚未提交(Committed) 的數(shù)據(jù),也不能返回臟數(shù)據(jù)。
可重復(fù)讀取(Repeatable Read): 禁止 不可重復(fù)讀取和臟讀取。但是有時(shí)可能出現(xiàn)幻影數(shù)據(jù),這可以通過(guò)“共享讀鎖”和“排他寫鎖”實(shí)現(xiàn),讀取數(shù)據(jù)事務(wù)將會(huì)禁止寫事務(wù)(但允許讀事務(wù)),寫事務(wù)則禁 止任何其他事務(wù)。在此隔離級(jí)下,用SELECT 命令讀取的數(shù)據(jù)在整個(gè)命令執(zhí)行過(guò)程中不會(huì)被更改。此選項(xiàng)會(huì)影響系統(tǒng)的效能,非必要情況最好不用此隔離級(jí)。
串行(Serializable): 也稱可串行讀。提 供嚴(yán)格的事務(wù)隔離,它要求事務(wù)序列化執(zhí)行,事務(wù)只能一個(gè)接著一個(gè)地執(zhí)行,但不能并發(fā)執(zhí)行。如果僅僅通過(guò)“行級(jí)鎖”是無(wú)法實(shí)現(xiàn)事務(wù)序列化的,必須通過(guò)其他機(jī) 制保證新插入的數(shù)據(jù)不會(huì)被剛執(zhí)行查詢操作事務(wù)訪問(wèn)到。事務(wù)隔離的最高級(jí)別,事務(wù)之間完全隔離。如果事務(wù)在可串行讀隔離級(jí)別上運(yùn)行,則可以保證任何并發(fā)重疊 事務(wù)均是串行的。
| 未授權(quán)讀取 | N | Y | Y | Y |
| 授權(quán)讀取 | N | N | Y | Y |
| 可重復(fù)讀取 | N | N | N | Y |
| 串行 | N | N | N | N |
Spring在TransactionDefinition接口中規(guī)定了7種類型的事務(wù)傳播行為,它們規(guī)定了事務(wù)方法和事務(wù)方法發(fā)生嵌套調(diào)用時(shí)事務(wù)如何進(jìn)行傳播:
package org.springframework.transaction.annotation; import org.springframework.transaction.TransactionDefinition;/*** Enumeration that represents transaction propagation behaviors for use* with the {@link Transactional} annotation, corresponding to the* {@link TransactionDefinition} interface.** @author Colin Sampaleanu* @author Juergen Hoeller* @since 1.2*/ public enum Propagation {/*** Support a current transaction, create a new one if none exists.* Analogous to EJB transaction attribute of the same name.* <p>This is the default setting of a transaction annotation.*/REQUIRED(TransactionDefinition.PROPAGATION_REQUIRED),/*** Support a current transaction, execute non-transactionally if none exists.* Analogous to EJB transaction attribute of the same name.* <p>Note: For transaction managers with transaction synchronization,* PROPAGATION_SUPPORTS is slightly different from no transaction at all,* as it defines a transaction scope that synchronization will apply for.* As a consequence, the same resources (JDBC Connection, Hibernate Session, etc)* will be shared for the entire specified scope. Note that this depends on* the actual synchronization configuration of the transaction manager.* @see org.springframework.transaction.support.AbstractPlatformTransactionManager#setTransactionSynchronization*/SUPPORTS(TransactionDefinition.PROPAGATION_SUPPORTS),/*** Support a current transaction, throw an exception if none exists.* Analogous to EJB transaction attribute of the same name.*/MANDATORY(TransactionDefinition.PROPAGATION_MANDATORY),/*** Create a new transaction, and suspend the current transaction if one exists.* Analogous to the EJB transaction attribute of the same name.* <p>Note: Actual transaction suspension will not work out-of-the-box on* all transaction managers. This in particular applies to JtaTransactionManager,* which requires the {@code javax.transaction.TransactionManager} to be* made available it to it (which is server-specific in standard J2EE).* @see org.springframework.transaction.jta.JtaTransactionManager#setTransactionManager*/REQUIRES_NEW(TransactionDefinition.PROPAGATION_REQUIRES_NEW),/*** Execute non-transactionally, suspend the current transaction if one exists.* Analogous to EJB transaction attribute of the same name.* <p>Note: Actual transaction suspension will not work on out-of-the-box* on all transaction managers. This in particular applies to JtaTransactionManager,* which requires the {@code javax.transaction.TransactionManager} to be* made available it to it (which is server-specific in standard J2EE).* @see org.springframework.transaction.jta.JtaTransactionManager#setTransactionManager*/NOT_SUPPORTED(TransactionDefinition.PROPAGATION_NOT_SUPPORTED),/*** Execute non-transactionally, throw an exception if a transaction exists.* Analogous to EJB transaction attribute of the same name.*/NEVER(TransactionDefinition.PROPAGATION_NEVER),/*** Execute within a nested transaction if a current transaction exists,* behave like PROPAGATION_REQUIRED else. There is no analogous feature in EJB.* <p>Note: Actual creation of a nested transaction will only work on specific* transaction managers. Out of the box, this only applies to the JDBC* DataSourceTransactionManager when working on a JDBC 3.0 driver.* Some JTA providers might support nested transactions as well.* @see org.springframework.jdbc.datasource.DataSourceTransactionManager通過(guò)創(chuàng)建Savepoint實(shí)現(xiàn)嵌套事務(wù),達(dá)到內(nèi)層事務(wù)若拋出異常(unchecked exception)則回滾到savepoint處,但不影響外層事務(wù);外層事務(wù)的回滾會(huì)一起回滾內(nèi)層事務(wù); */NESTED(TransactionDefinition.PROPAGATION_NESTED);private final int value;Propagation(int value) { this.value = value; }public int value() { return this.value; }} /** Copyright 2002-2012 the original author or authors.** Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at** http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.*/package org.springframework.transaction;import java.sql.Connection;/*** Interface that defines Spring-compliant transaction properties.* Based on the propagation behavior definitions analogous to EJB CMT attributes.** <p>Note that isolation level and timeout settings will not get applied unless* an actual new transaction gets started. As only {@link #PROPAGATION_REQUIRED},* {@link #PROPAGATION_REQUIRES_NEW} and {@link #PROPAGATION_NESTED} can cause* that, it usually doesn't make sense to specify those settings in other cases.* Furthermore, be aware that not all transaction managers will support those* advanced features and thus might throw corresponding exceptions when given* non-default values.** <p>The {@link #isReadOnly() read-only flag} applies to any transaction context,* whether backed by an actual resource transaction or operating non-transactionally* at the resource level. In the latter case, the flag will only apply to managed* resources within the application, such as a Hibernate {@code Session}.** @author Juergen Hoeller* @since 08.05.2003* @see PlatformTransactionManager#getTransaction(TransactionDefinition)* @see org.springframework.transaction.support.DefaultTransactionDefinition* @see org.springframework.transaction.interceptor.TransactionAttribute*/ public interface TransactionDefinition {/*** Support a current transaction; create a new one if none exists.* Analogous to the EJB transaction attribute of the same name.* <p>This is typically the default setting of a transaction definition,* and typically defines a transaction synchronization scope.*/int PROPAGATION_REQUIRED = 0;/*** Support a current transaction; execute non-transactionally if none exists.* Analogous to the EJB transaction attribute of the same name.* <p><b>NOTE:</b> For transaction managers with transaction synchronization,* {@code PROPAGATION_SUPPORTS} is slightly different from no transaction* at all, as it defines a transaction scope that synchronization might apply to.* As a consequence, the same resources (a JDBC {@code Connection}, a* Hibernate {@code Session}, etc) will be shared for the entire specified* scope. Note that the exact behavior depends on the actual synchronization* configuration of the transaction manager!* <p>In general, use {@code PROPAGATION_SUPPORTS} with care! In particular, do* not rely on {@code PROPAGATION_REQUIRED} or {@code PROPAGATION_REQUIRES_NEW}* <i>within</i> a {@code PROPAGATION_SUPPORTS} scope (which may lead to* synchronization conflicts at runtime). If such nesting is unavoidable, make sure* to configure your transaction manager appropriately (typically switching to* "synchronization on actual transaction").* @see org.springframework.transaction.support.AbstractPlatformTransactionManager#setTransactionSynchronization* @see org.springframework.transaction.support.AbstractPlatformTransactionManager#SYNCHRONIZATION_ON_ACTUAL_TRANSACTION*/int PROPAGATION_SUPPORTS = 1;/*** Support a current transaction; throw an exception if no current transaction* exists. Analogous to the EJB transaction attribute of the same name.* <p>Note that transaction synchronization within a {@code PROPAGATION_MANDATORY}* scope will always be driven by the surrounding transaction.*/int PROPAGATION_MANDATORY = 2;/*** Create a new transaction, suspending the current transaction if one exists.* Analogous to the EJB transaction attribute of the same name.* <p><b>NOTE:</b> Actual transaction suspension will not work out-of-the-box* on all transaction managers. This in particular applies to* {@link org.springframework.transaction.jta.JtaTransactionManager},* which requires the {@code javax.transaction.TransactionManager}* to be made available it to it (which is server-specific in standard J2EE).* <p>A {@code PROPAGATION_REQUIRES_NEW} scope always defines its own* transaction synchronizations. Existing synchronizations will be suspended* and resumed appropriately.* @see org.springframework.transaction.jta.JtaTransactionManager#setTransactionManager*/int PROPAGATION_REQUIRES_NEW = 3;/*** Do not support a current transaction; rather always execute non-transactionally.* Analogous to the EJB transaction attribute of the same name.* <p><b>NOTE:</b> Actual transaction suspension will not work out-of-the-box* on all transaction managers. This in particular applies to* {@link org.springframework.transaction.jta.JtaTransactionManager},* which requires the {@code javax.transaction.TransactionManager}* to be made available it to it (which is server-specific in standard J2EE).* <p>Note that transaction synchronization is <i>not</i> available within a* {@code PROPAGATION_NOT_SUPPORTED} scope. Existing synchronizations* will be suspended and resumed appropriately.* @see org.springframework.transaction.jta.JtaTransactionManager#setTransactionManager*/int PROPAGATION_NOT_SUPPORTED = 4;/*** Do not support a current transaction; throw an exception if a current transaction* exists. Analogous to the EJB transaction attribute of the same name.* <p>Note that transaction synchronization is <i>not</i> available within a* {@code PROPAGATION_NEVER} scope.*/int PROPAGATION_NEVER = 5;/*** Execute within a nested transaction if a current transaction exists,* behave like {@link #PROPAGATION_REQUIRED} else. There is no analogous* feature in EJB.* <p><b>NOTE:</b> Actual creation of a nested transaction will only work on* specific transaction managers. Out of the box, this only applies to the JDBC* {@link org.springframework.jdbc.datasource.DataSourceTransactionManager}* when working on a JDBC 3.0 driver. Some JTA providers might support* nested transactions as well.* @see org.springframework.jdbc.datasource.DataSourceTransactionManager*/int PROPAGATION_NESTED = 6;/*** Use the default isolation level of the underlying datastore.* All other levels correspond to the JDBC isolation levels.* @see java.sql.Connection*/int ISOLATION_DEFAULT = -1;/*** Indicates that dirty reads, non-repeatable reads and phantom reads* can occur.* <p>This level allows a row changed by one transaction to be read by another* transaction before any changes in that row have been committed (a "dirty read").* If any of the changes are rolled back, the second transaction will have* retrieved an invalid row.* @see java.sql.Connection#TRANSACTION_READ_UNCOMMITTED*/int ISOLATION_READ_UNCOMMITTED = Connection.TRANSACTION_READ_UNCOMMITTED;/*** Indicates that dirty reads are prevented; non-repeatable reads and* phantom reads can occur.* <p>This level only prohibits a transaction from reading a row* with uncommitted changes in it.* @see java.sql.Connection#TRANSACTION_READ_COMMITTED*/int ISOLATION_READ_COMMITTED = Connection.TRANSACTION_READ_COMMITTED;/*** Indicates that dirty reads and non-repeatable reads are prevented;* phantom reads can occur.* <p>This level prohibits a transaction from reading a row with uncommitted changes* in it, and it also prohibits the situation where one transaction reads a row,* a second transaction alters the row, and the first transaction re-reads the row,* getting different values the second time (a "non-repeatable read").* @see java.sql.Connection#TRANSACTION_REPEATABLE_READ*/int ISOLATION_REPEATABLE_READ = Connection.TRANSACTION_REPEATABLE_READ;/*** Indicates that dirty reads, non-repeatable reads and phantom reads* are prevented.* <p>This level includes the prohibitions in {@link #ISOLATION_REPEATABLE_READ}* and further prohibits the situation where one transaction reads all rows that* satisfy a {@code WHERE} condition, a second transaction inserts a row* that satisfies that {@code WHERE} condition, and the first transaction* re-reads for the same condition, retrieving the additional "phantom" row* in the second read.* @see java.sql.Connection#TRANSACTION_SERIALIZABLE*/int ISOLATION_SERIALIZABLE = Connection.TRANSACTION_SERIALIZABLE;/*** Use the default timeout of the underlying transaction system,* or none if timeouts are not supported.*/int TIMEOUT_DEFAULT = -1;/*** Return the propagation behavior.* <p>Must return one of the {@code PROPAGATION_XXX} constants* defined on {@link TransactionDefinition this interface}.* @return the propagation behavior* @see #PROPAGATION_REQUIRED* @see org.springframework.transaction.support.TransactionSynchronizationManager#isActualTransactionActive()*/int getPropagationBehavior();/*** Return the isolation level.* <p>Must return one of the {@code ISOLATION_XXX} constants* defined on {@link TransactionDefinition this interface}.* <p>Only makes sense in combination with {@link #PROPAGATION_REQUIRED}* or {@link #PROPAGATION_REQUIRES_NEW}.* <p>Note that a transaction manager that does not support custom isolation levels* will throw an exception when given any other level than {@link #ISOLATION_DEFAULT}.* @return the isolation level*/int getIsolationLevel();/*** Return the transaction timeout.* <p>Must return a number of seconds, or {@link #TIMEOUT_DEFAULT}.* <p>Only makes sense in combination with {@link #PROPAGATION_REQUIRED}* or {@link #PROPAGATION_REQUIRES_NEW}.* <p>Note that a transaction manager that does not support timeouts will throw* an exception when given any other timeout than {@link #TIMEOUT_DEFAULT}.* @return the transaction timeout*/int getTimeout();/*** Return whether to optimize as a read-only transaction.* <p>The read-only flag applies to any transaction context, whether* backed by an actual resource transaction* ({@link #PROPAGATION_REQUIRED}/{@link #PROPAGATION_REQUIRES_NEW}) or* operating non-transactionally at the resource level* ({@link #PROPAGATION_SUPPORTS}). In the latter case, the flag will* only apply to managed resources within the application, such as a* Hibernate {@code Session}.<< * <p>This just serves as a hint for the actual transaction subsystem;* it will <i>not necessarily</i> cause failure of write access attempts.* A transaction manager which cannot interpret the read-only hint will* <i>not</i> throw an exception when asked for a read-only transaction.* @return {@code true} if the transaction is to be optimized as read-only* @see org.springframework.transaction.support.TransactionSynchronization#beforeCommit(boolean)* @see org.springframework.transaction.support.TransactionSynchronizationManager#isCurrentTransactionReadOnly()*/boolean isReadOnly();/*** Return the name of this transaction. Can be {@code null}.* <p>This will be used as the transaction name to be shown in a* transaction monitor, if applicable (for example, WebLogic's).* <p>In case of Spring's declarative transactions, the exposed name will be* the {@code fully-qualified class name + "." + method name} (by default).* @return the name of this transaction* @see org.springframework.transaction.interceptor.TransactionAspectSupport* @see org.springframework.transaction.support.TransactionSynchronizationManager#getCurrentTransactionName()*/String getName();}PROPAGATION_REQUIRES_NEW :
啟動(dòng)一個(gè)新的, 不依賴于環(huán)境的 "內(nèi)部" 事務(wù).
這個(gè)事務(wù)將被完全 commited 或 rolled back 而不依賴于外部事務(wù), 它擁有自己的隔離范圍, 自己的鎖, 等等. 當(dāng)內(nèi)部事務(wù)開(kāi)始執(zhí)行時(shí), 外部事務(wù)將被掛起, 內(nèi)務(wù)事務(wù)結(jié)束時(shí), 外部事務(wù)將繼續(xù)執(zhí)行.
PROPAGATION_NESTED :
如果外部事務(wù) commit, 嵌套事務(wù)也會(huì)被 commit;
如果外部事務(wù) roll back, 嵌套事務(wù)也會(huì)被 roll back 。
開(kāi)始一個(gè) "嵌套的" 事務(wù), 它是已經(jīng)存在事務(wù)的一個(gè)真正的子事務(wù). 嵌套事務(wù)開(kāi)始執(zhí)行時(shí), 它將取得一個(gè) savepoint. 如果這個(gè)嵌套事務(wù)失敗, 我們將回滾到此 savepoint. 嵌套事務(wù)是外部事務(wù)的一部分, 只有外部事務(wù)結(jié)束后它才會(huì)被提交.
代碼例子:
@Transactional(propagation=Propagation.NESTED) @Transactional(propagation=Propagation.PROPAGATION_REQUIRES_NEW)ServiceA{@AutowiredServiceB serviceB;@Transactional(propagation=Propagation.NESTED)public void method1(){serviceB.method2();int i = 1/0;} }ServiceB{@Transactional(propagation=Propagation.NESTED)public void method2(){xxxxxx} }```因?yàn)閙ethod1使用 @Transactional(propagation=Propagation.NESTED),當(dāng)執(zhí)行method1時(shí),會(huì)拋出異常,method2()也會(huì)被回滾; 如果method2()用PROPAGATION_REQUIRES_NEW:``` ServiceB{ @Transactional(propagation=Propagation.PROPAGATION_REQUIRES_NEW)public void method2(){xxxxxx} }```那么method2不會(huì)因?yàn)閙ethod1拋出異常而回滾。 不管是什么類型的嵌套事務(wù),一個(gè)線程只有一個(gè)事務(wù),線程結(jié)束的時(shí)候才提交事務(wù),包括嵌套事務(wù),即使嵌套事務(wù)是REQUIRES_NEW,也不是嵌套事務(wù)的方法結(jié)束就提交事務(wù)的,一定是等到外部事務(wù)方法結(jié)束,整個(gè)線程結(jié)束才一起提交的。 在相同線程中進(jìn)行相互嵌套調(diào)用的事務(wù)方法工作于相同的事務(wù)中。如果這些相互嵌套調(diào)用的方法工作在不同的線程中,則不同線程下的事務(wù)方法工作在獨(dú)立的事務(wù)中。 而鎖存在于事務(wù)里,鎖的生命周期也是一個(gè)線程,在一個(gè)線程里可多次取得同一個(gè)鎖。如果事務(wù)加在外部方法A,在內(nèi)部方法里面有synchronized代碼塊B,那么當(dāng)B執(zhí)行完時(shí),事務(wù)還未提交,其他線程進(jìn)入synchronized代碼塊B后,讀取的庫(kù)存數(shù)據(jù)不是最新的。總結(jié)
以上是生活随笔為你收集整理的关于Spring的事务Transactional,锁同步,并发线程的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 乐观锁的概念
- 下一篇: setTimeout(function(