I’m still somewhat new to multithreading so maybe this is an easy answer, but I tried searching around with locks and synchronized methods but this isn’t working out right.
I have a system which connects to an ftp site and downloads an xml file to process. The application waits until the file on the ftp site is updated, if it isn’t updated it doesn’t do anything. If it is updated it downloads the xml file to start processing.
Before we process the xml we check the version of a file on the server, and the version of something in the database, if the versions aren’t the same, create a new thread and update the file on the server to the new version.
So in code it’s pretty much:
if(file.version.equals(db.version))
{
do work...
}
else
{
startUpdateThread();
}
private synchronized void startUpdateThread()
{
Runnable updateRunnable = new UpdateRunnable();
Thread updateThread = new Thread(updateRunnable);
updateThread.start();
}
The problem I’m having is that the xml file will change on the ftp site in the middle of updating the file on the server and still enter the startUpdateThread() method and by the time it’s finished I will have multiple threads trying to accomplish the same tasks.
My question I guess is, why is the syncrhonized method still being called even though it should be locked, and if I’m doing it wrong what is the correct way to approach this without creating multiple threads to accomplish the same tasks.
edit
A little further explanation of the system, the file on the server gets loaded into a cache when the application starts, so the file.version.equals is really from a cache. The file only needs to be regenerated once every few months it’s something that is done manually that I am going to make automated.
The file on the server and the xml file have nothing to do with each other, it just happens that this check is triggered when the application see’s the file on the server has changed (which is roughly every two minutes). To generate a new file and load it into cache takes about 10 minutes. So the check happens about 5 times, thus creating 5 threads, regenerating a file.
The desired result is:
Normal processing to continue with the xml file
ONE new thread being created to reload a totally seperate file on the server.
Hopefully that makes better sense…
Of course – the method
startUpdateThread()is syncronized but not the actual execution of the threads. The lock is released when theupdateThread.start()call terminates – and this is long before the worker thread finishes.Question is, what is your desired behaviour: if the remote file changes while you process it, then it is my understanding, that the changed file has a different number.
You could send a signal to the running worker thread to stop processing that file because it is already outdated. Or do you want the “second” worker thread to wait until the first one has finished? In that case, a ThreadPool with size 1 could help.