java中同步方法的问题

发布于 2024-10-07 15:45:14 字数 468 浏览 6 评论 0原文

我在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

秋风の叶未落 2024-10-14 15:45:14

仅仅因为它在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.

北凤男飞 2024-10-14 15:45:14

也许您有多个 dbAccess 实例? (synchronized 关键字在对象级别起作用,而不是在类级别起作用。)在这种情况下,您需要使方法静态(在您的情况下可能不可行),或者尝试使用静态锁来保护方法体,如下所示:

class dbAccess{  
    private final static Object o = new Object();

    public void getGUID(){  
        synchronized (o) {
            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
        }
    }  
}

Perhaps you have several instances of dbAccess? (The synchronized 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:

class dbAccess{  
    private final static Object o = new Object();

    public void getGUID(){  
        synchronized (o) {
            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
        }
    }  
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文