简体   繁体   中英

Java synchronized block not working

I have a multi threaded java application that retrieves usernames from a Postgresql database for processing.

I only want one account to be processed at a time by each thread so I have a column in my table which has the time stamp of last accessed and only accounts which have been accessed more than 30 seconds will be fetched. The SQL Query works below, I'm only posting it to be clear.

select * from account where (EXTRACT(EPOCH FROM (now() - last_accessed)) > 30 OR last_accessed is null) AND enabled = true order by random() limit 1

I have a synchronized block so only one thread can access the account retrieval process as the updating the time stamp takes a bid of time on the database.

public class TC extends Common implements Runnable
{
    RegularExpr reg = new RegularExpr();
    Database        db  = new Database();

    public void run()
    {
        while (true)
        {
            try
            {
                ArrayList<Object> accountInfo = null;

                synchronized (this)
                {
                    accountInfo = db.getAccount();
                    db.updateAccountAccessTime((String) accountInfo.get(0));
                    Thread.sleep(3000);
                }
                System.out.println((String) accountInfo.get(0));
                Thread.sleep(9999999);
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
        }
    }
}

My main class

public class Main
{
    public static void main(String[] args)
    {

        for (int i = 0; i < 3; i++)
        {
            System.out.println("Inside loop to create threads!");
            Thread newThread = new Thread(new TC());
            newThread.start();
        }
    }
}

But I still receive the same account when I run the program. What I am doing incorrectly?

Each thread is executing with a different instance of TC .

new Thread(new TC())

So when you do:

synchronized (this)

Each thread is synchronizing on a different object (different TC ), so they are not competing with each other at all. Essentially, the synchronized block becomes pointless.

I'm not sure how good of an idea this is, but what you are trying to do would be accomplished like this:

synchronized (TC.class)

or, perhaps a bit cleaner, by declaring a static member in the class and synchronizing on that:

private static final Object _lock = new Object();

....

synchronized(_lock)

The whole point of synchronization is, when there is a shared resource and multiple threads accessing it.

In your case,same TC instance can be passed into new Thread.then 3 threads start working on it.

Now the db operation needs to be protected, since you need to get account info and also update timestamp.so synchronize on a lock object specifically or this.

private Object lock = new Object();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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