eclipsesource / eclipsesource/J2V8
Restarting long-running NodeJS background service on Android crashes app
- Dominant language
- Java
- Stars
- 2.6k
- Forks
- 387
- PR merge metrics
- No merged PRs in 30d
Description
Suppose I have NodeJS running on a separate thread than the application UI (this is on android, where node runs in a separate thread in an android `Service`).
The node application runs an `express` webserver:
```javascript
const express = require("express");
const app = express();
app.get("/", (req, res) => {
res.json({ msg: "Nodejs on android says 'hi'." });
});
app.listen(5000);
process.on('SIGTERM', function () {
server.close(function () {
process.exit(0);
});
});
```
Then what is the cleanest way to stop the node thread from the application thread?
```java
private Thread thread;
public void start() {
thread = new Thread(new Runnable() {
@Override
public void run() {
NodeJS nodeJs = NodeJS.createNodeJS();
// ... initialization code here
File appIndex = new File(jsPath, "index.js");
nodeJs.exec(appIndex);
while (nodeJs.isRunning() && !Thread.currentThread().isInterrupted()) {
nodeJs.handleMessage();
}
try {
nodeJs.release();
} catch (IllegalStateException e) {
throw new RuntimeException("Failed to release NodeJS", e);
}
}
});
thread.start();
}
public void stop() {
if (thread != null && thread.isAlive() && !thread.isInterrupted()) {
thread.interrupt();
}
}
```
The above does not work as the while loop is blocked on `handleMessage` until the next server request.
I have seen the suggestion on https://github.com/eclipsesource/J2V8/issues/231 to use an additional `thread2` that sleeps until interrupted (from UI thread) and then calls `nodeJS.getRuntime().terminateExecution()` on the `nodeJs` from `thread`.
But does that work here, and it is a method with quite some overhead only to implement `NodeService.stop()`. And does it close the node app gracefully?
I will continue looking for a better way, but maybe this has an easy answer..
Contributor guide
Assessment
This issue has not been assessed yet.