I have Shutdown hook that i attach to runtime
Runtime.getRuntime().addShutdownHook(new ShutDownHook(false));
Here is a shutDownHook Class
public class ShutDownHook extends Thread {
private final boolean interupt;
public ShutDownHook(boolean interupt) {
this.interupt = interupt;
}
#Override
public void run() {
if (interupt) {
return;
}
System.out.println("ShutdownHook Execution");
DbUtil.insertIntoDailyStats(MainDataModel.downloadedBytesSessionProperty().getValue());
MainDataModel.getInstance().loginProfile.getPreferences().putLong(
Info.PreferenceData.PREF_USER_DAILY_STAT_DOWNBYTE, MainDataModel.downloadedBytesTodayProperty().get());
System.out.println("ShutdownHook Execution finished");
}
}
And i close my application from System tray icon with a method
exit.addActionListener((ActionEvent e) -> {
try {
GlobalScreen.unregisterNativeHook();
System.exit(0);
} catch (NativeHookException ex) {
ex.printStackTrace();
}
});
Application closes bud hook execution didnt went thru, any idea why?
I know there are cases when ShutdownHook doesnt execute bud im closing my application with System.exit(0); that shoud be all safe and sound?
Ok i found a problem i had multiple ShutDownHooks hooked in for some reason this one didnt executed , i removed all beside one and now everything works ok.Maybe too much of a load.
Works flawlessly , also if you use netbeans dont use RED TERMINATION BUTTON , - just a note.That way you never get execution of SDH.
Related
I have a simple thread like this.
public class CameraThread extends Thread {
private AtomicBoolean runCamera;
public CameraThread(AtomicBoolean runCamera) {
this.runCamera = runCamera;
}
#Override
public void run() {
while (Main.RUNTHREAD) {
while (runCamera.get()) {
Platform.runLater(() -> {
System.out.println("Hello");
threadSleep();
});
}
}
}
private void threadSleep() {
try {
Thread.sleep(2000L);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
And when I set runCamera to runCamera.set(true) utside from the thread, the whole GUI freezes and I cannot do anything.
This is a minimal example and I can't get it to work properly.
I have used RunLater command before, but this time, I'm sitting at a Dell precision M6400 machine from 2007. Could it happen that this machine cannot handle threads with Java?
Or how can I solve this issue?
To reproduce this issue, just type the following:
wget https://github.com/DanielMartensson/Darknet-Data-Creator/archive/main.zip
unzip Darknet-Data-Creator-main.zip
cd Darknet-Data-Creator-main
mvn javafx:run
Then click on Scan button, select a web camera (USB, laptop camera) and then press Save to folder button. Just select some arbitary folder. Then press Open camera button
The issue is that you are using Thread.Sleep() inside Platform.runLater(...), which means that you are sleeping the GUI, not your camera thread.
Try this instead, note how runLater is outside of the Platform.runLater code:
#Override
public void run() {
while (Main.RUNTHREAD) {
while (runCamera.get()) {
Platform.runLater(() -> {
System.out.println("Hello");
});
//Now thread sleep is outside of runLater:
threadSleep();
}
}
}
The only thing that should go inside the runlater is things that directly change the GUI. Any calculation, sleeping, processing, file reading etc should be kept separate.
I'd been googling around for a way for me to send in command to a running Java program, but most of the post suggested to implement listener or wrap the program with a Jetty (or other server) implementation.
Is there a way to do this without adding additional dependencies?
The scenario is, i have a Java program which will be running indefinitely, and which will spawn a few running threads. I would like to be able to run a script to stop it, when it needs to be shut down, somewhat like the shutdown script servers tend to have. This will allow me to handle the shutdown process in the program. The program runs in a linux environment.
Thank you.
Implemented the shutdown hook and so far it looks good. The implementation codes:
final Thread mainThread = Thread.currentThread();
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
logger.info("Shut down detected. Setting isRunning to false.");
if(processors != null && !processors.isEmpty()){
for (Iterator<IProcessor> iterator = processors.iterator(); iterator.hasNext();) {
IProcessor iProcessor = (IProcessor) iterator.next();
iProcessor.setIsRunning(false);
try {
iProcessor.closeConnection();
} catch (SQLException e1) {
logger.error("Error closing connection",e1);
}
}
}
try {
mainThread.join();
} catch (InterruptedException e) {
logger.error("Error while joining mainthread to shutdown hook",e);
}
}
});
Thanks for the suggestion.
My while(true) is only running once, so I'm trying to add breakpoints to see what's going on, but they never seem to be reached within my run(). I'm using IntelliJ. In the debugger there's a "Threads" tab. Do I need to do something in that tab like select the right thread in order for my breakpoint to be reached? I also see thread names and am wondering how I can find the right thread in this list.
public class MyClass extends ServerWorkflowProcess<OtherClass> {
private ExecutorService executorService = Executors.newSingleThreadExecutor();
...
#Override
public void bootup() {
logger.info("Booting up: " + this);
BackgroundProcess backgroundImpositioner = new BackgroundProcess(this.getCollection());
executorService.submit(backgroundImpositioner);
}
#Override
public void shutdown() {
executorService.shutdown();
}
}
Background process
public class BackgroundProcess implements Runnable {
protected volatile Logger logger = Logger.getLogger(BackgroundImpositioner.class.getName());
Collection<ImpositionWorkstation> impositionWorkstations;
public BackgroundImpositioner(Collection<ImpositionWorkstation> impositionWorkstation) {
this.impositionWorkstations = impositionWorkstation;
}
public void run() {
while(true) {
logger.info("looping");
for (ImpositionWorkstation workstation : impositionWorkstations) {
if (workstation.canAcceptWork()) {
//go do work in another thread so we're not blocking this
workstation.getWorkFromQueue();
try {
workstation.doWork();
} catch (ImpositionException e) {
logger.severe(e.getMessage());
}
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
logger.severe("Background impositioner was interrupted");
}
}
}
}
Side note: the console shows "looping", so I know it gets executed once. The breakpoint never gets hit and it doesn't execute more than once.
It happened to me once that i couldn't make Intellij Idea stop in breakpoints. Basically the problem is that once a thread is stopped in a breakpoint the others won't stop.
There is a setting in the breakpoints properties dialog that prevents this.
Right click on a breakpoint and select 'View Breakpoints'.
On the dialog select a breakpoint.
You will notice on the right of suspend checkbox 2 radio buttons: All and Thread. Select All. Aditionally you can make that the default (Make Default button on the right). The default value will be used for any new breakpoints you add. The old ones need to be changed manually.
EDIT
Additional info on the Intellij help site: Breakpoint options
Don’t let exceptions slip through silently. Use the Future returned by the submit method.
Future<?> f=executorService.submit(backgroundImpositioner);
try {
f.get();
} catch(Exception ex) {
ex.printStackTrace();
}
Then you know more.
The code above is just for finding your actual problem. For production environments you wouldn’t wait for completion but rather log the exception when it occurred, e.g.:
executorService.execute(new FutureTask<Object>(backgroundImpositioner, null)
{
#Override
protected void done() {
if(!isCancelled()) try {
get();
} catch(InterruptedException ex) {
throw new AssertionError("on completed task", ex);
} catch(ExecutionException ex) {
logger.log(Level.SEVERE, "in background task", ex.getCause());
}
}
});
For a reason beyond me, I was not able to breakpoint the while(true) line, but was able to drop breakpoints elsewhere within the run().
If there's no exception thrown inside the run method, i can only assume that one of the calls never returns.
Can you put output statements after every single call to see how far you get?
I guess either workstation.canAcceptWork() or workstation.doWork() is the culprit.
I've met a similar problem that IntelliJ never hits my breakpoint in the run() method of a Runnable class. I found that the only position for the breakpoint to be hit is at the line of public void run() {.
I have an android application, that have one thread, which will run after each 1 minute.
So my problem is, when i click one button, i have to reset the app, that means, it'll be
a fresh app.
So now when i clicked on that button, all the database and shared preference will clear.
But the thread will start again.
Now am using like this
if (killthread.isAlive()) {
killthread.interrupt();
}else {
// Here what'll i do, I mean how to kill that thread, which in sleep mode.
}
Thank you
vishnu
Thanks for the reply, Here when i click that button, that will come to the else part, but after 1 minute, the thread will start.So how to stop that in stage?
That will be something to do with the thread itself. My bet is that you have coded it to ignore the interrupt.
OK, here's the code from your comment.
public void run() {
while (true) {
try {
Thread.sleep(60000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
}
}
}
What this does is to catch and silently ignore the exception that occurs when the thread is interrupted ... and just keep going.
If you want it to stop on an interrupt it should be this ... or something equivalent.
public void run() {
while (true) {
try {
Thread.sleep(60000);
} catch (InterruptedException e) {
return;
}
}
}
If a Thread is not alive it means
1) it's dead / finished. You cannot / dont need to do anything.
2) it is newly created / havent started yet. That is Thread.start() has not been called yet. In this case Thread.interrupt() will have no effect. The only thing you can do is some custom logic - notify the code that is going to start the thread that it's not needed anymore
There is a console Java application which is supposed to run until it is stopped by Ctrl+C or closing the console window. How that application can be programmed to execute a clean up code before exit?
You could use a Shutdown Hook.
Basically you need to create a Thread which will perform your shutdown actions, and then add it as a shutdown hook. For example:
class ShutdownHook extends Thread
{
public void run()
{
// perform shutdown actions
}
}
// Then, somewhere in your code
Runtime.getRuntime().addShutdownHook(new ShutdownHook())
A Shutdown hook is the way to go, but be aware that there is no guarantee that the code is actually executed. JVM crashes, power failures, or a simple "kill -9" on your JVM can prevent the code from cleaning up. Therefore you must ensure that your program stays in a consistent state even if it has been aborted abruptly.
Personally, I simply use a database for all state-storage. Its transactions model makes sure that the persistent storage is in a sane state no matter what happens. They spend years making that code fool-proof, so why should I waste my time on problems already solved.
Program to delete temp file bat.bat when program is exited:
public class Backup {
public static void createBackup(String s)
{
try{
String fileName ="C:\\bat"+ ".bat";
FileWriter writer=new FileWriter(fileName);
String batquery="cd C:\\Program Files\\MySQL\\MySQL Server 5.0\\bin"
+ "\nmysqldump -uroot -proot bankdb > \""+s+".sql\""
+"\nexit";
writer.append(batquery);
writer.close();
}
catch(Exception e){e.getMessage();}
try{
Process p =Runtime.getRuntime().exec("cmd /c start C:\\bat.bat");
}
catch(Exception e){e.getMessage();}
ShutDownHook sdh=new ShutDownHook();
Runtime.getRuntime().addShutdownHook(sdh);
}
}
class ShutDownHook extends Thread
{
public void run()
{
try
{
File f=new File("c:/bat.bat");
f.delete();
}
catch(Exception e){e.getMessage();}
}
}
The code written inside a Threads run() method will execute when the runtime object terminates...
class ShutdownHookclass extends Thread {
public void run() {
// perform shutdown actions
}
}
//could be written anywhere in your code
Runtime.getRuntime().addShutdownHook(new ShutdownHookclass())