I have a project which requires logging in my router from time to time and make some changes. In eclipse I have a separate project which deals with all the things I need changed and I have that in the build path of my main project which is a multi threaded project. My problem is that sometimes two threads try to access the router which messes things up. Is there anything I can do that only one thread can access a certan part of my code.
This is the related code for the main multithreaded application
if (totalLogins > 10)
{
IpManager.rebootRouter();
Thread.sleep(4000);
totalLogins = 0;
composedMessagesWithThisIP = 0;
}
And in the other project this is what I have
public synchronized static void rebootRouter()
{
try
{
//code related to restart modem
}
catch (Exception e)
{
}
}
So what I have done is made the method synchronized but I believe from time to time more than one thread access the “rebootRouter” method. Which causes problems in my main application.
What is the best way and most effective way to make IpManager.rebootRouter() be executed by one thread only?
Regards!
synchronizedguarantees that only one thread can enter the block at a time, but AFAIR the same thread can enter the block multiple times (so threads don’t deadlock against themselves), and if a thread is blocked because another thread is in there then it may run immediately after the first thread leaves the synchronized block.First I’d throw logging at the entry and exit points of the routine.
I’d check to see that you don’t have any recursion going on, and make sure that the calls really are running at the same time. Also, remember if there’s any asynchronous work or callbacks the synchronized block may be exited.