I have a task that compress an image, which use many many loops inside it:
private void writeCompressedData() {
int i, j, r, c, a, b;
loat[][] inputArray;
for (r = 0; r < minBlockHeight; r++) {
for (c = 0; c < minBlockWidth; c++) {
xpos = c * 8;
pos = r * 8;
for (comp = 0; comp < jpegObj.numberOfComponents; comp++) {
inputArray = (float[][]) jpegObj.components[comp];
for (i = 0; i < jpegObj.VsampFactor[comp]; i++) {
for (j = 0; j < jpegObj.HsampFactor[comp]; j++) {
xblockoffset = j * 8;
yblockoffset = i * 8;
for (a = 0; a < 8; a++) {
for (b = 0; b < 8; b++) {
// Process some data and put to inputArray
}
}
// Encode Huffman block
}
}
}
}
}
}
I run this method inside a normal thread like this:
new Thread(new Runnable() {
@Override
public void run() {
writeCompressedData();
}
});
Or run inside a background worker thread
TaskExecutor.queueRunnable(new Runnable() {
@Override
public void run() {
writeCompressedData();
}
});
The problem is: this method sometimes go wrong and cause infinite loops when receive invalid input. In that case, it will run forever and hurt the CPU even when the device's screen turn off which increase device's temperature (and if I use worker thread it also blocks other tasks inside waiting queue).
I think I need to set a timeout to terminate long running task. What's the best way to achieve this in normal Java thread? Does RxJava support it?
I know what I need to fix is the "wrong" method, not just terminate it. But for the big apps, it's hard to control other developer's code, and the first thing I need is avoid affecting users.