I'm having trouble with memory in a j2me application. (see another question)
I discovered that one class has a loop that doesn't stop until the application is closed. This loop is consuming all the memory available.
I didn't make this class so I don't know why things was done this way. So any suggestions are welcome.
Here is a simplified version of the class:
import java.util.TimerTask;
public class SomeClass extends TimerTask implements Runnable {
private boolean running = false;
private Thread thread;
public void invokeThread() {
running = true;
thread = new Thread(this);
thread.start();
}
public void run() {
while(running) {
try {
Thread.sleep(800);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
doSomeStuff();
}
}
private void doSomeStuff() {
// do some stuff that consumes my memory
}
public void dispose() {
running = false;
}
}
Another class calls SomeClass.invokeThread() and wait for some user response (this already spend some memory).
When the users ends inputting data this another class calls dispose() and the while loop doesn't stop, wait some minutes or try to navigate a bit more the application and you get an OutOfMemoryError.
Can you help me?
thanks
Try adding keyword volatile to the variable running:
private volatile boolean running = false;
This is done to ensure that your thread always uses master-copy of the variable, not the locally stored.
Without seeing what's going on inside of doSomeStuff() it's impossible to tell why the loop doesn't terminate. Obviously the routine is expecting that dispose() is eventually going to be called or that running will eventually be set to false manually. If the loop isn't terminating, then neither of these things are happening. You should examine the logic within doSomeStuff() to figure out why.
Related
I want to create a thread to make some HTTP requests every few seconds and is easy to pause and resume at a moments notice.
Is the way below preferred, safe and efficient?
public class Facebook extends Thread {
public boolean running = false;
public void startThread() {
running = true;
}
public void stopThread() {
running = false;
}
public void run() {
while(true) {
while(running) {
//HTTP Calls
Facebook.sleep(2000);
}
}
}
}
Your Code:
In your example, the boolean should be volatile boolean to operate properly. The other issue is if running == false your thread just burns CPU in a tight loop, and you probably would want to use object monitors or a Condition to actually wait idly for the flag to become true again.
Timer Option:
I would suggest simply creating a Timer for this. Each Timer implicitly gets its own thread, which is what you are trying to accomplish.
Then create a TimerTask (FacebookTask below is this) that performs your task and from your main control class, no explicit threads necessary, something like:
Timer t;
void resumeRequests () {
if (t == null) { // otherwise its already running
t = new Timer();
t.scheduleAtFixedRate(new FacebookTask(), 0, 2000);
}
}
void pauseRequests () {
if (t != null) { // otherwise its not running
t.cancel();
t = null;
}
}
Note that above, resumeRequests() will cause a request to happen immediately upon resume (as specified by the 0 delay parameter); you could theoretically increase the request rate if you paused and resumed repeatedly in less than 2000ms. This doesn't seem like it will be an issue to you; but an alternative implementation is to keep the timer running constantly, and have a volatile bool flag in the FacebookTask that you can set to enable/disable it (so if it's e.g. false it doesn't make the request, but continues checking every 2000ms). Pick whichever makes the most sense for you.
Other Options:
You could also use a scheduled executor service as fge mentions in comments. It has more features than a timer and is equally easy to use; they'll also scale well if you need to add more tasks in the future.
In any case there's no real reason to bother with Threads directly here; there are plenty of great tools in the JDK for this job.
The suggestion to using a Timer would work better. If you want to do the threading manually, though, then something more like this would be safer and better:
class Facebook implements Runnable {
private final Object monitor = new Object();
public boolean running = false;
public void startThread() {
synchronized (monitor) {
running = true;
monitor.notifyAll();
}
}
public void stopThread() {
synchronized (monitor) {
running = false;
}
}
#Override
public void run() {
while(true) {
try {
synchronized (monitor) {
// Wait until somebody calls startThread()
while (!running) {
monitor.wait();
}
}
//HTTP Calls
Thread.sleep(2000);
} catch (InterruptedException ie) {
break;
}
}
}
}
Note in particular:
You should generally implement Runnable instead of subclassing Thread, then use that Runnable to specify the work for a generic Thread. The work a thread performs is not the same thing as the thread itself, so this yields a better model. It's also more flexible if you want to be able to perform the same work by other means (e.g. a Timer).
You need to use some form of synchronization whenever you want two threads to exchange data (such as the state of the running instance variable). There are classes, AtomicBoolean for example, that have such synchronization built in, but sometimes there are advantages to synchronizing manually.
In the particular case that you want one thread to stop work until another thread instructs it to continue, you generally want to use Object.wait() and a corresponding Object.notify() or Object.notifyAll(), as demonstrated above. The waiting thread consumes zero CPU until it is signaled. Since you need to use manual synchronization with wait/notify anyway, there would be no additional advantage to be gained by using an AtomicBoolean.
Edited to add:
Since apparently there is some confusion about how to use this (or the original version, I guess), here's an example:
class MyClass {
static void main(String[] args) {
FaceBook fb = new FaceBook();
Thread fbThread = new Thread(fb);
fbThread.start();
/* ... do stuff ... */
// Pause the FaceBook thread:
fb.stopThread();
/* ... do more stuff ... */
// Resume the FaceBook thread:
fb.startThread();
// etc.
// When done:
fbThread.interrupt(); // else the program never exits
}
}
I Would recommend you to use a guarded blocks and attach the thread to a timer
I'm hoping someone can help me with this. I've been searching for about a week for an answer to this issue, with no avail.
I currently have a custom thread class that implements Runnable, which I'd like to pause upon a key press. Based on my research, I've learned that the best way to go about this is by using wait() and notify(), triggered by a key that's using a key binding.
My question is, how can I get this to work? I can't seem to set up a key binding without something going wrong, and how I might implement wait() and notify() without running into a deadlock is beyond me.
wait and notify are meant to be used for synchronization. It seems to me that you wanted to use methods like Thread.suspend(), Thread.stop() and Thread.resume(), but those have been deprecated for the risk of problems with lock that they cause.
The solution is to use a helper variable that the thread will check periodically to see if it should be running, otherwise, yield(or sleep)
Why not to use suspend, stop or resume: http://docs.oracle.com/javase/6/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html
Simple solutions:
How to Pause and Resume a Thread in Java from another Thread
http://www.tutorialspoint.com/java/java_thread_control.htm
Here is a simple snapshot that might get you started :
class PausableThread extends Thread {
private volatile boolean isPaused;
#Override
public void run() {
while (true /* or some other termination condition */) {
try {
waitUntilResumed();
doSomePeriodicAction();
} catch (InterruptedException e) {
// we've been interrupted. Stop
System.out.println("interrupted. Stop the work");
break;
}
}
}
public void pauseAction() {
System.out.println("paused");
isPaused = true;
}
public synchronized void resumeAction() {
System.out.println("resumed");
isPaused = false;
notifyAll();
}
// blocks current thread until it is resumed
private synchronized void waitUntilResumed() throws InterruptedException {
while (isPaused) {
wait();
}
}
private void doSomePeriodicAction() throws InterruptedException {
System.out.println("doing something");
thread.sleep(1000);
}
}
So, you start your thread somewhere new PausableThread().start();
And then in your button/keypress listeners on UI thread you call
in OnPauseKeyPress listener mPausableThread.pauseAction();,
and for OnResumeKeyPress you call mPausableThread.resumeAction();
To stop the tread altogether, just interrupt it : mPausableThread.interrupt();
Hope that helps.
Okay I'm sure I'm missing something simple here but can't see it. I'm using a flag to end a thread and then joining it to clean up neatly, but the join never finishes it just gets stuck waiting. There is currently nothing in the thread's run loop so it isn't getting stuck in a separate loop.
Thread:
package com.nox.willywars;
public class GameThread extends Thread {
//{{Variables
private boolean running;
//}}
//{{Getters/Setters
public void setRunning(boolean running) {
this.running = running;
}
//}}
//{{Constructor
public GameThread() {
running = false;
}
//}}Constructor
//{{Public methods
#Override
public void run() {
while(running) {
///...CODE GO HERE
}
}
public boolean isRunning() {
return running;
}
//}}
}
Code that fails to stop it:
//{{Lifecycle methods
#Override
public void create() {
//LOAD! Probably debug temp
TileFactory.load();
mapScreen = new MapScreen();
setScreen(mapScreen);
gameThread = new GameThread();
gameThread.setRunning(true);
gameThread.start();
}
#Override
public void resize(int width, int height) {
}
#Override
public void pause() {
killGameThread();
}
private void killGameThread() {
if(gameThread != null) {
if(gameThread.isAlive() && gameThread.isRunning()) {
gameThread.setRunning(false);
boolean retry = true;
while(retry) {
try {
gameThread.interrupt();
gameThread.join();
retry = false;
} catch (InterruptedException e) {}
}
}
gameThread = null;
}
}
//}}
Currently it reaches gameThread.join() and gets stuck there, waiting for the thread to finish. Am I missing something here? As I understand the thread should finish once running is set to false and then joining should happen normally because it's already stopped.
Edit: Added some more code from the class that runs GameThread. Pause() is where KillGameThread is executed. I've made running volatile but it's had no effect.
I found another weird symptom too: Some people suggested looking at what's inside GameThread when it's stuck, so I went into the debugger. While join() is stuck I suspended the GameThread thread and saw it was on while(running), and running was definitely false. Then when I stepped over the code it exited the loop and finished correctly, seemingly caused by my debugging. It's as if the thread is somehow suspended?
first set the running flag as volatile
private volatile boolean running;
What does game thread do exactly, maybe it has blocked by some I/O operation.
and if the game thread doesn't sleep/wait/join, so interrupting it is useless.
you need to share the game thread code.
As user2511414 pointed out, try with using volatile. In short, this will make sure the value od running is always accessed directly and not cached.
It setting volatile won't solve the situation, he problem most probably lays in the code section of a GameThread#run method that you commented out.
You can try using jstack or jvisualvm to get a Thread Dump of the thread you're trying to join.
This will at least show you where is it hanging, and may lead you to a solution.
The running flag is not properly synchronised. This could (in theory) result in the thread not noticing the state change ... due to the way that the Java memory model works. You should either declare it as volatile or always access and update it in synchronized method calls (or synchronized blocks).
But (IMO) the real problem is in the way (actually the ways) that you are telling the thread to stop, and haw the thread is checking or responding.
If you are going to use a flag to tell the thread to stop, then the thread needs to check that flag frequently. If the thread could spend an indefinitely long amount of time doing something else between the checks, then it may never notice that it needs to stop.
If you are going to use Thread.interrupt() then:
Your code should be calling Thread.isInterrupted() to test the thread's "interrupted" status instead of an ad-hoc flag. Furthermore, it should be testing the status regularly.
Your code need to make sure that it handles the InterruptedException and InterruptedIOException properly. This applies all the way up the call stack.
Note that calling Thread.interrupt() doesn't actually interrupt the thread in most cases. In most cases, it just sets a flag that needs to be tested manually. The only cases you get more than that is in certain blocking calls; e.g. Object.wait(...) and some IO calls.
You've left out most of the code where these things ought to happen. The best we can say is that the problem is most likely in code you haven't shown us.
I've been searching for a solution for a long time, but I wasn't able to find one, so I'll ask my question here.
I have a thread which is started when the program starts and supposed to be idle until it is enabled by the application. Simple code example:
private class UpdaterThread extends Thread {
private static final int UPDATE_RATE = 50;
private Timer updateTimer = new Timer();
private boolean enabled;
public void run() {
while (!closeRequested) {
// If this is uncommented, the thread works as it's supposed to.
// System.out.print("");
if (enabled) {
Snapshot next = getNextSnapshot(1f / UPDATE_RATE);
System.out.println("Got next Snapshot");
updateTimer.sync(UPDATE_RATE);
System.out.println("Push");
currentSnapshot = next;
}
}
}
public void enable() {
enabled = true;
}
public void disable() {
enabled = false;
}
}
When you read a variable, which the JIT believes you didn't modify, it inlines the value. If you then modify the value later, it is too late, the value has been embedded in the code.
A simple way to avoid this is to use volatile but you would still have the problem than the thread is busy waiting for the value to change and there doesn't appear to be a good reason to do this. Another option is to add code which confuses the JIT do it doesn't do this optimisation. An empty synchronized block is enough but a friendlier way is to use Thread.sleep() which at least doesn't use up all your CPU.
I suggest using a volatile fields and sleeping with a period of 10-100 ms. However a simpler option is to not start the thread until it is needed.
since run() is called when the thread is started, you could just wait until later in the program to start it, also threads do not extend "Thread" but implements "Runnable" so the class definition would look like:
public class UpdaterThread implements Runnable
hope it helps :D
I have made a java program with GUI and I want a stop button functionality in which when a user clicks on the stop button, the program must be stopped.
In my program, the main thread starts other 10 threads and I want that whenever the stop button has been clicked all the 10 threads must be stopped before the main thread.
Second, I also want that whenever any thread of those 10 threads is stopped, it must first close all the resources it had opened before like connection to a database etc.
I have implemented the code as answered by ........
Now there is one problem.
My thread class is like this:
public class ParserThread implements Runnable {
private volatile boolean stopped = false;
public void stopTheThread() {
stopped = true;
}
:
:
}
And below is the main thread that starts 10 threads from the function start()
public class Main() {
Thread [] threads;
public void start() {
for(int i = 0; i < 10; i++) {
threads[i] = new Thread(new ParserThread());
}
}
public void stop() {
// code to stop all the threads
}
}
Now I want to call the stop method of the ParserThread to set "stopped = true" to stop the thread. I want this thing to be done for all the 10 threads.
How can I call that stop method. I want it to be done in the stopAllThreads() method of the Main class.
Generally speaking, the way to do this is to have each of the other threads periodically check a flag. Often background threads loop, waiting for work - they just have to check the flag each time they go round a loop. If they're using Object.wait() or something similar to be told that there's more work, the same notification should be used to indicate that the thread should stop too. (Don't just spin until you're stopped - that will suck CPU. Don't just use sleep - that will delay termination.)
That allows all threads to terminate cleanly, releasing resources appropriately. Other options such as interrupt() and the deprecated destroy() method are much harder to control properly, IMO. (Interrupting a thread is better than hard-aborting it, but it has its own set of problems - such as the interruption is only processed at certain points anyway.)
EDIT: In code, it would look something like:
// Client code
for (Task task : tasks) {
task.stop();
}
// Threading code
public abstract class Task implements Runnable {
private volatile boolean stopped = false;
public void stop() {
stopped = true;
}
protected boolean shouldStop() {
return stopped;
}
public abstract void run();
}
Your tasks would then subclass Task. You would need to make it slightly more complicated if you wanted the stop() method to also notify a monitor, but that's the basic idea.
Sample task:
public class SomeTask extends Task {
public void run() {
while (!shouldStop()) {
// Do work
}
}
}
I don't think the answer solve the issue. here the code:
public class SomeTask extends Task {
public void run() {
while (!shouldStop()) {
// Do work
}
}
}
But how to handle if the "Do work" hang and does not return? In this case, the while cannot check the flag. The Thread still cannot stop.
The possible solution to this might be using Process.
Have a controller object which has a flag whether the threads should stop or not and each thread checks the controller periodically and exits if stop button is clicked (for example if you are transferring a file, then after each block is received/sent, check if stop is clicked).