Reputation: 481
I have Java app which reads data from IoT devices. For I have example smart thermometer:
public class Thermometer{
private final String ip;
public Thermometer(String ip) {
this.ip = ip;
}
public void startReading () {
Thread readThread = new Thread(() -> {
while (true) {
try {
//reading, writing data to DB
} catch (Exception e) {
//logging
}
}
});
readThread.start();
}
}
In my main I add all my IoT devices and start their reading threads:
new Thermometer("192.168.1.100").startReading();
new Thermometer("192.168.1.101").startReading();
After a while (last time I've tryed it was about 12 hours) my main thread stops so all my threads stop too. My log file (log4j2) has single line about this:
com.foo.Main - null
Probably complete stack trace was printed to sys.err. I will try to catch it and update post.
Why does it happen? How can I start all my threads so they will run forever?
UPD. Main class:
public class Main {
public static void main(String[] args) {
new Thermometer("192.168.1.100").startReading();
new Thermometer("192.168.1.101").startReading();
}
}
UPD2. Starting script:
nohup java -Dlog4j.configurationFile=$PATH_TO_LOG4J2_XML -jar $PATH_TO_REEVE_JAR >> /home/buger/reeve/nohup.log 2>>&1 &
echo $! > $PATH_TO_PID
echo_and_log "Successfully started! PID = `cat $PATH_TO_PID`"
Upvotes: 1
Views: 164
Reputation: 7166
I think something happened to your reader threads. Maybe an exception , achem, an Error
killed them. I suggest you to debug that.
Meanwhile, here is an example code that sort of proves my theory:
public class Main {
public static void main(String[] args) {
Thread thread1 = new Thread(() -> {
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("--> thread 1");
}
});
Thread thread2 = new Thread(() -> {
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("--> thread 2");
}
});
thread1.start();
thread2.start();
System.out.println("--> main thread about to finish");
}
}
This produces the following output:
--> main thread about to finish
--> thread 2
--> thread 1
--> thread 1
--> thread 2
...
Upvotes: 1