简体   繁体   English

Java中同步方法的问题

[英]problem with synchronized method in java

I have following implementation in Java where I am trying to use a synchronized method: 我在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 */
     }  
}

The portion between /* */ represent some sql queries. / * * /之间的部分代表一些sql查询。 The implementation has 10 threads. 该实现有10个线程。 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? 而且,这是正确的方法吗?

Just because it is synchronised in java, does not mean it is synchronised on the database. 仅仅因为它在Java中已同步,并不意味着它已在数据库上同步。 This method needs to run in a database transaction with read locking enabled. 此方法需要在启用了读取锁定的数据库事务中运行。

Perhaps you have several instances of dbAccess ? 也许您有几个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: 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
        }
    }  
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM