[英]java multi threaded application to update DB
I have a DB which has 100 entries need to update certain table colum entry which is dynamically requires update. 我有一个数据库,其中有100个条目需要更新某些动态需要更新的表列条目。
Essentially all the 100 entries they collect the data from disk and update the DB tables.In order to get the db/disk info they have to get the lock which tries till gets the lock in the while loop. 基本上所有100个条目都从磁盘收集数据并更新DB表。为了获取db / disk信息,它们必须获取锁,该锁将尝试直到在while循环中获取锁为止。 Once they get the lock then only can update the latest diskinfo to the DB. 一旦他们获得了锁定,则只能将最新的diskinfo更新到数据库。
I have a following pesudo code which essentially does the above said work sequentially. 我有一个下面的伪代码,它基本上按顺序完成上述工作。 I want to run them multithreaded way so that parallel work can be done. 我想以多线程方式运行它们,以便可以并行工作。 Could you please guide me.I am completely new to the java multithread program. 你能指导我吗?我对Java多线程程序是完全陌生的。
Thanksin advance for your help. 在此先感谢您的帮助。
while(true)
{
for(int i=0,i<100;i++)
{
//Get the info from Disk
String diskInfo=getDiskInfo(i);
//Get the info from DB table
String dbInfo=getDBInfo(i);
if (! diskInfo.equals(dbInfo))
{
//Update DB with diskInfo
boolean status=UpdateDB(i);
}
}
sleep(2000);
}
//Get the info from Disk
public String getDiskInfo()
{
//Get the disk
//lock the disk wait if busy
while(true)
{
//get disk lock
sleep(2000);
}
//fetch data
String data = "test";
//unlock disk
return data;
}
public String getDBInfo()
{
//Get the DB
//lock the DB wait if busy
while(true)
{
//get DB lock
sleep(2000);
}
//fetch data
//select data from X;
String data = "test";
//unlock disk
return data;
}
public boolean UpdateDB()
{
//Get the DB
//lock the DB wait if busy
while(true)
{
//get DB lock
sleep(2000);
}
//fetch data
if(!getDiskInfo(),equals(getDBInfo())
{
//lock the DB wait if busy
while(true)
{
//get DB lock
sleep(2000);
}
status=UpdateDB();
}
else
{
//no update needed
status=false;
}
return status;
}
I would not write code to do this. 我不会编写代码来做到这一点。 I'd synchronize the Java objects or use the database facilities for isolation to do what you want. 我将同步Java对象或使用数据库工具进行隔离以执行您想要的操作。
As far as I can see you only want one loop (the outer most loop) Multi-threaded programs work similar to single threaded programs in that its not a good idea to have infinite loops all over the place. 据我所知,您只希望一个循环(最外面的循环),多线程程序的工作方式类似于单线程程序,因为在整个地方都存在无限循环不是一个好主意。
I would have one checking thread which adds tasks to a thread pool in your first loop and remove the rest. 我将有一个检查线程,该线程在第一个循环中将任务添加到线程池中,并删除其余线程。
Multithreading is hard. 多线程很难。
That sleep() call and inifinite loops better be for filling because you are going to find nasty surprises if you try that with multithreading. 该sleep()调用和无限循环最好用于填充,因为如果您尝试使用多线程,则会发现令人讨厌的惊喜。
That said your code should be relatively easy to transform to a multithreading one. 也就是说,您的代码应该相对容易地转换为多线程代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.