java中同步方法的问题
我在 Java 中有以下实现,我尝试使用同步方法:
class dbAccess{
public synchronized void getGUID(){
counter=/*Access last count from txn_counter table */
/*Insert a unique value to txn_counter table based on the acquired value of counter */
/*Insert new counter value to GUID_log table */
}
}
/* */ 之间的部分代表一些 sql 查询。该实现有 10 个线程。我希望每次返回的计数器值都是唯一的。但多次运行会返回相同的计数器值。
如果我做错了什么,你能指出吗?而且,这是正确的方法吗?
I have following implementation in Java where I am trying to use a synchronized method:
class dbAccess{
public synchronized void getGUID(){
counter=/*Access last count from txn_counter table */
/*Insert a unique value to txn_counter table based on the acquired value of counter */
/*Insert new counter value to GUID_log table */
}
}
The portion between /* */ represent some sql queries. The implementation has 10 threads. I was hoping that counter value returned everytime would be unique. But it so happens that multiple runs return same value of counter.
Can you please point out if I am doing anything wrong. And, is it the right way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
仅仅因为它在java中同步,并不意味着它在数据库上同步。此方法需要在启用读锁定的数据库事务中运行。
Just because it is synchronised in java, does not mean it is synchronised on the database. This method needs to run in a database transaction with read locking enabled.
也许您有多个
dbAccess
实例? (synchronized
关键字在对象级别起作用,而不是在类级别起作用。)在这种情况下,您需要使方法静态(在您的情况下可能不可行),或者尝试使用静态锁来保护方法体,如下所示:Perhaps you have several instances of
dbAccess
? (Thesynchronized
keyword works on object level not on class level.) In that case you need to make the method static (may not be feasible in your situation), or try to have a static lock protecting the method body, like this: