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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…