This question continues this question.
I am trying to stop thread that inserts rows to dabase, but I always got an exception
This part of code shows my thread's logic
public void run() {
String number = "";
try {
while (!Thread.currentThread().isInterrupted()) {
number = generateNumber();
database.insertOrUpdateRow(number);
}
} catch (SQLException ex) {
LOGGER.error("exception while inserting number " + number + " " + ex.getMessage());
}
}
I have googled how to stop thread correctly and found that I should just flag that thread is stopped. So, this is what I got
public boolean stop() {
try {
Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
for (Thread t : threadSet) {
if (t != null) {
if (t.getName().contains("generate")) {
t.interrupt();
LOGGER.info(t.getName()+" is stopped");
}
}
}
} catch (Exception e) {
LOGGER.error("Exception when call stop: " + e.toString());
}
return true;
}
My stacktrace
[INFO] [qtp1804418913-32] INFO se.homework.hwbs.tasks.un.server.NumberQtyService
Impl - generate37 is stopped
[INFO] [generate37] ERROR se.homework.hwbs.tasks.un.server.threads.InsertRowThre
ad - exception while inserting number 34587 transaction rollback: serialization
failure
[INFO] [qtp1804418913-33] ERROR se.homework.hwbs.tasks.un.server.database.Databa
se - error select cnt by numberjava.sql.SQLTransactionRollbackException: transac
tion rollback: serialization failure
[INFO] [qtp1804418913-34] ERROR se.homework.hwbs.tasks.un.server.database.Databa
se - error select cnt by numberjava.sql.SQLTransactionRollbackException: transac
tion rollback: serialization failure
Thread stops, everything works, but this exceptions make me feel bad. Why are they happens? How to stop thread when I work with database in correct way? Database is HsqlDB.