Java Thread.wait() warnings - java

When i enclose Thread.wait() in a while loop my IDE (NetBeans) tells me that this may cause perfomance issues, how can it and is there a way arround it?
Example:
while (timing){
Thread.wait(10);
foo++;
}
//Started in a seperate thread before activating.
EDIT: Thanks for the help, I will try to use the 'ScheduledExecutorService' instead!

You probably wanted to just make the thread sleep, and that is the name of the method you needed to call.
You called Object#wait(), which is a thread coordination method, and you used an explicit timeout on it (a rather short one). My guess is that NetBeans is warning you about that timeout because normally we use Object#wait without a timeout, and if we use the timeout, we don't wait in a loop.
Now, NetBeans will also warn you about using Thread.sleep() in a loop because normally, if you want to schedule a repeated task (that is what you are doing), you will use a ScheduledExecutorService. That service is able to serve a lot of different scheduled tasks around your application, all with a single thread. Writing Thread.sleep() explicitly in a loop needlessly hogs a whole thread (a heavyweight system resource) to do nothing but sleep most of the time.

Related

What is a preferred way of closing a third-application thread without waiting for it to complete?

I am currently running the JAR that I cannot change, and sometimes it simply gets stuck for no good reason. I have tried finding the ways to interrupt the thread, stop the thread, etceteras, but no luck.
Each solution offered was about doing the complete exit or waiting for a thread to complete.
What I want to do is to simply close the thread, exactly when the timeout completes, and carry on with the program.
What I do not want to do is use the while loop with a timeout, java.util.concurrent.Future, System.exit, and make a Thread.interrupt call.
None of these will help!
You can't forcibly stop a thread in mid-execution. The Thread.destroy() method would have done that, but it was never implemented, and its documentation explains why it would be unsafe to use even if it worked.
There are some other deprecated methods like Thread.stop() and Thread.suspend() which may actually work, but they're also unsafe to use; again, their documentation explains why.
Telling the thread that it should terminate itself, and then waiting for it to do so, is the only safe way to stop a thread.
As an workaround, you could run your task in an entirely separate process, so that you can destroy it when you want it to stop. That is safe, since processes are isolated from each other and destroying the child process can't leave the parent process in an unstable state.
Interacting with a separate process is more difficult, though, since you can't share variables between processes like you can with threads. You'd need to send messages through the process's input and output streams.
Actually, you can't really solve this!
What I mean is: even if you would manage to kill "your" thread that you used to trigger the 3rd party code - you have no way of killing threads or processes created by the code you are invoking.
If you want to be absolutely sure to kill all and anything, you might have to look into rather complex solutions like:
instead of just using a thread, you create a new process with a new JVM B
in that JVM B, you can call that library
but of course, that requires that you put additional code around; so that "your" code in JVM A can talk to "your" code in JVM B
And now you might be able to tear down that process, and all artifacts belonging to it. Maybe.
And seriously: to be really really sure that the 3rd party library didn't kick of anything that you can't stop; you might even have to run that JVM inside some kind of container (for example a docker instance). That you could tear down and be sure that everything is gone.
Long story short: I think there is no way to absolutely control the threads created in a thread. If you need that level of control, you need to look into "outsourcing" those calls.
You can use Executor for this. It allows you to submit tasks (e.g. runnable) and executes those tasks parallely. Also, once you call shutdown(), it lets you configure the timeout and kills all the workers if they are not finished by that time. An example would look like this:
ExecutorService executor = Executors.newFixedThreadPool(1);
executor.execute(() -> {
//logic to call the method of third party jar
});
//Other business logic
executor.awaitTermination(1, TimeUnit.MINUTES);
executor.shutdownNow();
TimeUnit is an enum, with values like SECONDS, HOURS, MINUTES etc (here's javadoc) so you can configure different time units. A couple of points:
Once shutdownNow is called, no new tasks will be accepted (i.e. you can't call execute or submit) and existing tasks will be stopped. So, we are basically waiting for a minute for tasks to be complete and if it is not complete, we are killing that task.
awaitTermination throws InterruptedException (as it interrupts the threads internally if they are not finished) so you will have to wrap it inside try-catch block.
Here's javadoc for Executor.

Java Threads, join() taking too long?

So I have some code, I am creating 6 threads, in my main thread, that run some code. I start the threads. I then call join() on the threads, so that the main thread waits for them all to die before continuing with execution.
Now, I am using some really basic and most likely inaccurate way to measure how long my code takes to run. Just calls to get the system time at the start, the end, and then print the difference.
Lets say it is taking, for example, around 500ms to run all of my code.
I decided to remove the calls to join() for each thread, and instead I just told my main thread to sleep for 20ms. This resulted in my code finishing in around 200ms, and the main thread managed to continue with execution with the proper data from the worker threads - i.e. the 6 worker threads must have finished in that 20ms wait.
THEREFORE, why is it taking so much longer when I use .join on each worker thread? Naturally, I cannot keep the call in the main method to sleep(20), and would rather use something like join()'s
The problem with multi-threaded bugs is you can appear to be working when it is not working reliably. It is possible your threads are doing something you don't need at the end, or you joining thread doesn't use the results right away. In any case, I suggest you wait for the result correctly.
BTW I would use an ExecutorService as this allows you to recycle your threads and wait for just the results you need in the form of a Future<MyResult> note this also captures and Exception/Error thrown as well.
It is also possible that your code is simply not getting finished if you take out the joins. If your main function exits without joining on all of its threads, then it is possible some are getting set as daemon threads via setDaemon(), which would stop the program cleanup from waiting on them.
Do you own all the code involved?

How do I suspend java threads on demand?

I am working on a multithreaded game in java. I have several worker threads that fetch modules from a central thread manager, which then executes it on its own. Now I would like to be able to pause such a thread if it temporarily has nothing to execute. I have tried calling the wait() method on it from the thread manager, but that only resulted in it ignoring the notify() call that followed it.
I googled a bit on it too, only finding that most sites refer to functions like suspend(), pause(), etc, which are now marked a deprecated on the java documentation pages.
So in general, what is the way to pause or continue a thread on demand?
You can use an if block in the thread with a sentinal variable that is set to false if you want to halt the thread's action. This works best if the thread is performing loops.
Maybe I'm missing the point, but if they have nothing to do, why not just let them die? Then spawn a new thread when you have work for one to do again.
It sounds to me like you're trying to have the conversation both ways. In my (humble) opinion, you should either have the worker threads responsible for asking the central thread manager for work (or 'modules'), or you should have the central thread manager responsible for doling out work and kicking off the worker threads.
What it sounds like is that most of the time the worker threads are responsible for asking for work. Then, sometimes, the responsibility flips round to the thread manager to tell the workers not to ask for a while. I think the system will stay simpler if this responsibility stays on only one side.
So, given this, and with my limited knowledge of what you're developing, I would suggest either:
Have the thread manager kick of worker threads when there's stuff to do and keep track of their progress, letting them die when they're done and only creating new ones when there's new stuff to do. Or
Have a set number of always existing worker threads that poll the thread manager for work and (if there isn't any) sleep for a period of time using Thread.sleep() before trying again. This seems pretty wasteful to me so I would lean towards option 1 unless you've a good reason not to?
In the grand tradition of not answering your question, and suggest that You Are Doing It Wrong, I Offer this :-)
Maybe you should refactor your code to use a ExecutorService, its a rather good design.
http://download.oracle.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html
There are many ways to do this, but in the commonest (IMO), the worker thread calls wait() on the work queue, while the work generator should call notify(). This causes the worker thread to stop, without the thread manager doing anything. See e.g. this article on thread pools and work queues.
use a blocking queue to fetch those modules using take()
or poll(time,unit) for a timed out wait so you can cleanly shutdown
these will block the current thread until a module is available

Stopping a thread that could be looping forever

I have a program where I compile java code a user types into a text field, and then run it. A run the code in a seperate thread, so that the GUI they use to input the source code doesn't get locked up.
The GUI has an abort button that should stop the thread. My issue is that I need to stop the compiling thread no matter what is going on inside of it, which means I must account for a case where the thread is caught in an infinite loop (due to user error), and it cannot properly end itself using a safe flag. I've read up on many solutions that involve using a flag of some kind, but they aren't available to me because of this looping issue. I need to have the thread stop and the memory it's using freed (I can't just let it sit in the background forever, unless that is the only solution left). Any advice or alternative solutions? Hopefully some fresh perspectives could help squash this issue.
Edit:
Here's a sample bit of user submitted code:
public class RunMe extends SomethingThatRuns {
public void run() {
int i = 0;
while (i = 0) {
//Prepare to get stuck!
}
}
}
I'll compile this class, and then run it. This is where it will get stuck, and the run() method can never finish, or even loop to check a flag.
You can run it in a new JVM so you can kill it when you want.
Thinking about security this may be a good thing to do too.
Call stop() on the thread.
Yes, this is a deprecated method. However, it really shouldn't be "deprecated", it should be "dangerous." In some circumstances, however, there's really no choice but to use it, and the invocation of an "agent" provided by a user is one of those cases.
Make sure that your program doesn't use any data that are manipulated by this user thread; or, if you do, devise some transactional mechanism to exchange data safely between the threads.
Even this method isn't guaranteed to terminate the thread. For example, the user can catch the resulting Throwable and ignore it. Or, the thread implementation might not respond to stop() calls if the thread is in some native code. But it's your best chance.
The core issue here is the fact that the code even allows an infinite loop to be entered as part of user error. Fix that, and everything else will become easier to deal with.
Properly-behaving threads should usually terminate themselves gracefully when there's no work to do (or return quietly to a thread pool to ask for more work, if that's your application's design). If you feel like you need to have one thread forcefully kill another then you've likely got a fundamental design issue. It's fine to have one thread tell another, "Hey, you should terminate now so that I can join with you..." because that allows your threads to clean things up as they finish. Forcefully destroying threads just isn't the right way to manage these situations.
You can use them to insert a interrputed check in every loop and maybe in other places too.
I can see two options:
As you compile the user code you can edit it before. You may use
ANTLR to parse and modify the code.
There are bytecode manipulation frameworks like ASM that allow you to manipulate code that is already
compiled.
I don't think it is easy but it might be a way.
interupt(); the Thread in the gui
and in the code that the thread runs regularly check for Thread.interrupted() and throw an exception when you do especially inside loops
At a high level, you are asking how one thread might go about stopping another thread. To that end, see this SO question Stopping a Thread in Java?.

Is there anything dangerous about using Thread.currentThread.sleep() in my main code?

in my code I'm using
Thread.currentThread().sleep(sleepTime);
in the main (non Thread object) portion of the code.
It appears to be working fine, but I'm worried that there might be some hidden pitfall that will bite me in the ass later.
Is there a better way to make your main process sit around for a while? or is this the prescribed methodology?
EDIT:
In answer to why I'm doing it this way...
I have a process that connects via HTTP or FTP to remote hosts and does stuff.
In other words...
stuff...
connect to remote...
do stuff with remote connection...
close connection...
more stuff...
repeat as necessary.
I've found that in very very rare instances, the connection just goes off into la la land. It doesn't fail, it doesn't throw any exception, it just goes away.
And it's blocking, so there's no in-line way to set a timer.
So, my solution is to do this...
stuff...
start new thread with connection in it...
go into an infinite loop with a timer in the MAIN process (not in the spawned thread) and wait for either
a) the connection thread to complete its task and set some flag to "done"
or
b) wait some preset amount of time and if the connection thread has not reported that it's finished, kill it and move on.
It is in the main process that I intend to sleep for some time, wake up, and see if the MAX_WAIT_TIME has expired. If not, go back to sleep and wait some more.
It seems much more efficient (on the processor) than sitting in standard while loop, since that would really interfere with the connection thread's business of doing what it needs to do.
I guess my question really is... is there anything unsafe about this approach. I see from the answers that, given what I'm doing, it looks like there isn't. Perhaps I should have asked if there is a more standardized approach?
What kind of application are you writing? It's rarely a good idea, and it's a particularly bad idea if you're writing a client GUI - while the thread is sleeping, it won't be responsive.
If you could give more of an indication why you need to pause and the kind of application you're writing, that would help.
One other thing - your call should really be:
Thread.sleep(sleepTime);
Calling it via currentThread() makes it look like it's an instance method, but it's not - it's just a normal static method. You can't make any other thread sleep.
You should see if your IDE has an option to make calling static methods via a reference into a warning or error - it leads to misleading code (like this).
There's no pitfall. It will sleep for as long as you tell it to.
There may or may not be a pitfall in the idea of your application falling asleep for a prolonged period of time.
It's not dangerous, but in 99+% of cases when you think you need it, you really don't. What are you trying to do?
Well, Thread.sleep is a static method so it is very misleading. Also you can't be woken up cleanly (you can interrupt, but I'd dispute that that is clean) in case you need the action to shutdown.
If you decide to use Thread.sleep, ensure that you handle the InterruptedException appropriately.
What do you mean the connection just "goes away"? Sure there's no inline way to set a timer, but you can set a connect timeout AND read timeouts if you want.
Create the socket with the no-args constructor, the call connect(SocketAddress, int) so that you can set a timeout (in milliseconds). If the connection can't be established in that time, an exception is thrown.
And you can call setSoTimeout() before connecting so that any calls to read() will only block for the amount of time you specify, instead of forever. If data can't be read in the time you specified, an exception is thrown.
AFAIR Thread.sleep() wastes CPU time while Object.wait(long timeout) does not. So you should always use Object.wait(long timeout) instead. Although I can't find any footage that supports my thesis, I reckon that when switching to Object.wait(long timeout) calls we received a large performance gain.
People often use Timer to perform delayed events but I prefer the ScheduleExecutorService. You can use the same thread pool for all your timeout actions. (You can have a thread pool of size 1)

Categories