Thread - synchronized

同步的关键是多个线程对象竞争同一个共享对象,使无序的多个线程有序地排队。

Example 1:

public class Thread06_sync {

	public static void main(String[] args) {
//		new Thread06_sync().test01();
		new Thread06_sync().new Test02(new Object()).test02();
	}

	// 同步失败,原因:不是同步同一个对象
	public void test01() {
		for (int i = 1; i <= 3; ++i) {
			new Thread(new Runnable() {
				public synchronized void run() {
					for (int i = 1; i <= 5; ++i) {
						System.out.println("id:"
								+ Thread.currentThread().getId() + ",i:" + i);
					}
				}
			}).start();
		}
	}

	// 同步成功,原因:同步同一个对象
	public class Test02 {

		private Object thisThread;

		public Test02(Object thisThread) {
			this.thisThread = thisThread;
		}

		public void test02() {
			for (int i = 1; i <= 3; ++i) {
				new Thread(new Runnable() {
					public void run() {
						synchronized (thisThread) {
							for (int i = 1; i <= 5; ++i) {
								System.out.println("id:"
										+ Thread.currentThread().getId() + ",i:" + i);
							}
						}
					}
				}).start();
			}
		}
	}

}

第一个例子,如果不同的synchronized object, 则不能正确lock住代码片段。


Example 2:

public class Thread04_static {

	// volatile 只是可见一致性,非原子性(也就是无写锁),仍然有机会有重复uniqueNumber的输出
	public volatile static long uniqueNumber = 0;	
	static int threadNumber = 5;
	static AtomicInteger testNum = new AtomicInteger(0);
	static List<Long> resultList = new ArrayList<>(300);
	private final static ReentrantLock lock = new ReentrantLock();
	
	public static void main(String[] args) {
		testThread01();
	}
	
	// CountDownLatch
	public static void testThread01() {
		try {
			CountDownLatch doneSignal = new CountDownLatch(50);
			for (int i = 0; i < threadNumber; i++) {
				Thread thread = new Thread(new Thread04_static().new TestThread01(doneSignal));
				thread.setName("t_" + i);
				thread.start();
			}
			// 由于thread的无序性,不加await的话, 有可能运行下面语句时thread还没运行,resultList有可能是空值
			doneSignal.await();
			int i = 1;
			for (Long result : resultList) {
				System.out.println("result_" + i + ":" + result);
				++i;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	// 静态类及非静态同步、锁测试
	public class TestThread01 implements Runnable {
		
		private CountDownLatch doneSignal;
		public TestThread01(CountDownLatch doneSignal) {
			this.doneSignal = doneSignal;
		}
		public void run() {
			try {
				// 第一个同步block/ReentrantLock:这里的同步无预期效果(即有重复的uniqueNumber出现),因为getUniqueNum是类静态方法
//				synchronized (this) {
//				lock.lock();
					for (int i = 0; i < 10; i++) {
//						System.out.println(testNum.addAndGet(1));
						// 有重复的testNum出现, 原因:testNum是原子的,但下面的语句不原子
//						System.out.println("Thread:" + Thread.currentThread().getName() + ", testNum:" + testNum + ", i:" + i);
						resultList.add(getUniqueNum(2));
						doneSignal.countDown();
					}
					// 空行不一定每十条记录输出一次,因为它不在下面的静态同步block
					System.out.println("");
					Thread.sleep(1000);
//				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
//				lock.unlock();
			}
		}
	}
	
	public static Long getUniqueNum(int len) {
		// 第二个同步block/ReentrantLock:静态类同步block/lock,实现无重复uniqueNumber输出
//		synchronized (TestThread01.class) {
		try{
			lock.lock();
			if (len < 1) {
				return null;
			}
			if (uniqueNumber < (Math.pow(10, len) - 1)) {
				uniqueNumber++;
			}
			System.out.println("Thread:" + Thread.currentThread().getName()
					+ ", uniqueNumber:" + uniqueNumber);
			return uniqueNumber;
		} finally {
			lock.unlock();
		}
//		}
	}
}

第二个例子,static 和 非static的不同,也会导致lock的失败。

<think>好的,我现在要解决用户遇到的Hibernate异常:“org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread”。首先,我需要理解这个问题的根本原因。根据用户提供的引用,特别是引用[4]提到,这个问题通常是因为跨过Service层直接调用Dao层导致的,因为事务通常是在Service层管理的[^4]。另外,引用[2]指出,当无法获取到事务同步的Session时,Hibernate会抛出这个异常[^2]。 接下来,我需要考虑可能的解决方案。根据引用[5],配置事务注解驱动可能是一个解决方法,比如在Spring配置文件中添加`<tx:annotation-driven transaction-manager="transactionManager"/>`[^5]。此外,引用[3]中的示例代码显示,直接使用openSession()而不是getCurrentSession()可能会绕过这个问题,但这样做可能需要手动管理事务,不够理想[^3]。 首先,应该检查是否在Service层正确配置了事务管理。确保Service方法上使用了@Transactional注解,这样Spring才能代理事务。然后,Dao层应该通过getCurrentSession()来获取Session,而不是openSession(),因为后者不会与事务绑定。 另外,检查Spring的配置文件是否正确配置了事务管理器和注解驱动。例如,是否声明了PlatformTransactionManager,以及是否启用了注解驱动的事务管理。 还需要确认Hibernate的版本是否与Spring版本兼容,特别是Hibernate 4及以上版本可能存在配置差异。如果配置正确,但仍然存在问题,可能需要调整SessionFactory的配置,确保它与Spring的事务管理正确集成。 总结可能的解决步骤: 1. 确保Service层使用@Transactional注解。 2. 检查Dao层是否使用getCurrentSession()而非其他方式获取Session。 3. 验证Spring配置中的事务管理器和注解驱动是否正确设置。 4. 避免在Dao层直接调用非事务方法。 同时,用户提供的引用[3]中提到的直接使用openSession()并手动管理事务虽然可行,但不符合最佳实践,可能导致事务管理混乱,应优先使用Spring声明式事务管理。</think>### 解决方案:Hibernate无法获取事务同步Session的排查与修复 #### 问题原因分析 该异常通常由以下原因导致: 1. **未正确配置事务管理**:Service层未启用事务管理,导致Dao层无法通过`getCurrentSession()`获取与事务绑定的Session。 2. **直接调用Dao层**:跨过Service层直接调用Dao层方法,绕过了事务代理机制。 3. **错误使用Session获取方式**:在Dao层使用`openSession()`而非`getCurrentSession()`,导致Session未与事务绑定。 --- #### 分步解决方案 ##### 1. 确保Service层启用事务管理 - **添加@Transactional注解**:在Service类或方法上添加Spring事务注解,声明事务边界。 ```java @Service public class UserServiceImpl implements UserService { @Autowired private UserDao userDao; @Transactional // 关键注解,启用事务管理 @Override public void updateUser(User user) { userDao.update(user); } } ``` ##### 2. 检查Dao层Session获取方式 - **使用`getCurrentSession()`**:Dao层必须通过`sessionFactory.getCurrentSession()`获取Session,确保Session与事务绑定。 ```java @Repository public class UserDaoImpl implements UserDao { @Autowired private SessionFactory sessionFactory; // 正确方式:获取事务同步的Session private Session getSession() { return sessionFactory.getCurrentSession(); } @Override public void update(User user) { getSession().update(user); // 无需手动提交事务 } } ``` ##### 3. 验证Spring事务配置 - **配置事务管理器与注解驱动**:在Spring配置文件中(如`applicationContext.xml`)添加以下内容: ```xml <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"/> </bean> <!-- 启用注解驱动的事务管理 --> <tx:annotation-driven transaction-manager="transactionManager"/> ``` ##### 4. 避免跨层调用 - **通过Service层调用Dao**:确保所有数据库操作经过Service层,禁止Controller直接调用Dao。 --- #### 其他注意事项 - **Hibernate与Spring版本兼容性**:Hibernate 4+需使用`HibernateTransactionManager`,而非旧版`Hibernate3TransactionManager`。 - **事务传播行为**:若需嵌套事务,可通过`@Transactional(propagation = Propagation.REQUIRED)`指定传播机制。 - **手动回滚事务**:在事务方法中捕获异常后,可调用`TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()`手动回滚。 --- ### 相关问题 1. **如何在Spring中配置声明式事务管理?** 2. **@Transactional注解有哪些常用属性?** 3. **Hibernate的`getCurrentSession()`和`openSession()`有什么区别?** 4. **事务传播机制有哪些类型?如何选择?**
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值