Java Application must be closed when in sleep mode - java

I want to keep my application stopped if computer goes to sleep mode. I have use thread in my application and it performs some task after specific interval.
Is it possible to stop program execution when the computer sleep?
If yes, please provide some solution or Java classes for the same.

Not using Java. You'd have to write an operating system hook (in say C++) that triggers on whatever signal your operating system sends when it puts the computer to sleep and then tries to gracefully shut down your Java program (probably by sending it some sort of a message on a TCP port that your program will listen to).

Related

How can I kill a Java program that is left hanging (in Windows )?

Suppose that in Java I have a simple Echo Client/Server pair. I start up the Server process, but I never actually start the Client process.
What I'd like to do, is have a third program (call it "Parent"), that will automatically kill this Server program after 30 seconds of being idle.
Could I use Powershell to do this? Or do I need to use C or other programming?
Yes, as long as you have a good way to:
1) uniquely identify the server process
2) determine server is idle
If there will never be two (or more) instances of the server process, then you can identify the process by name (make sure your process has a unique name!)
Determining that the server is idle may be tricky (hence the comments to implement the server stopping itself without resorting to a "parent" process). However if the server is memory or CPU intensive when it is active you may be able to take advantage of that to distinguish idle from busy. You can use get-process (gps) to determine the process' current CPU and memory use. The trick will be to know how long it's been idle if it currently looks idle. To do this reliably you will need to poll with gps more frequently than it takes the server to process a request. Otherwise you may poll before the server is busy, then the server is busy, and then you poll again when it's idle. But you'll think it was idle the whole time.
You can avoid the dilemma above by having the server change something when it knows it has been idle for 30 seconds, like the window title. (But if you're doing that why not just have the server terminate itself?)
Once the PS script determines the server is idle then get-process -name yourServerProcess|stop-process will stop the server process. Specify "yourServerProcess" without the .EXE at the end. If you get a permissions error, then run PS as administrator.

How to gracefully shutdown a Java application that is terminated as a result of closing the command line from which it was executed?

There is a an answered question on Best Way to Gracefully Shutdown a Java Command Line Program. A shutdown hook does the job in case when a program was terminated by Ctrl+C.
My question is how to gracefully exit if the command line itself is closed during the execution of a Java program? I tested with shutdown hook but it didn't work in this case. I cannot find out what happens to the virtual machine in this scenario. Is the process and all its threads killed instantly?
What kind of signal does closing command line produce?
So, how this particular problem can be solved?
EDIT: The problem concerns Windows environment.
Logically, SIGHUP (terminal hangup) should be raised.
Actually, I've just checked my guess with a simple shell script. Yes, when a user closes a terminal emulator in which an application was started (and from which it wasn't detached), then the application receives SIGHUP. So set up a SIGHUP handler and react accordingly. A usual behaviour is to terminate an application, but your intents may be different.
Also if your Java application performs any STDIN/STDOUT operations, it should be closed or at least re-cofigured when HUP is received, because an attempt to read/write from non existing terminal would lead to SIGPIPE and/or program block.
For Windows take a look at Catch Windows terminal closing on running process
Edit for windows environment:
I don't have much experience on windows environment but if you want your application to keep running, it's generally deployed as Windows service (it's similar to daemon on Linux). You would typically start/stop/restart service through a utility that lists all services (I think you get to it via control panel -> Administrative Tools -> Services. I would guess that issuing a "stop" via this tool would signal a graceful shutdown. And if you kill the service via the task manager, then it won't be a graceful shutdown.
Is this a Linux based or Windows based environment? In Linux, if you ran the program in background (and exit the shell with 'exit' command), it'll continue running. You can put your application in the background by adding an & at the end. Also, a lot of applications/services run in the background. If you execute a Tomcat startup script with the startup.sh command, it'll continue running in the background even when you quit the terminal you launched it from. On windows too, the concept should be similar.
In terms of closing application, you use kill command on Linux systems. kill command on a process sends a SIGTERM signal to it. Applications can implement code to intercept SIGTERM and shutdown gracefully on detecting a SIGTERM. If the application doesn't handle SIGTERM gracefully, then it won't respond to a SIGTERM / kill. In that case, you need to explicitly give it a SIGKILL (kill -9) to kill it forcefully. In that case, graceful shutdown is not possible.
In Java, there is a special Runtime method for that : addShutdownHook.
This allows you to initialize a thread that the JVM will try to run just before stopping. It is the place to put any cleanup you want to execute even in case of Ctrl-C of closing of parent window. Extract from javadoc : A shutdown hook is simply an initialized but unstarted thread. When the virtual machine begins its shutdown sequence it will start all registered shutdown hooks in some unspecified order and let them run concurrently. When all the hooks have finished it will then run all uninvoked finalizers if finalization-on-exit has been enabled. Finally, the virtual machine will halt.
The shutdown hook is call even if the program ends normally. In that case, it is cleaner to remove the registered hook before exiting with removeShutdownHook (still a method from Runtime)
EDIT :
In the case of Windows environment, there are no real signals, but special callbacks when system is shutting down. AFAIK, the system hook is correctly called in that case, but I admit I never really tested that. In Windows, processes can be asked to terminate with 2 ways :
PostQuitMessage function posts a WM_QUIT message in process event loop - normally the process should exit, but it can do its cleanup (equivallent of Unix SIG_TERM)
TerminateProcess immediately stops the process and all its threads (equivallent of Unix SIG_KILL)
Console processes can use a ConsoleControlHandler that can intercept Ctrl-C, Ctrl-Break or Ctrl-Close events. First two are generated through keyboard, last is generated when the user closes the console. But normally, the Oracle JVM should use the system hook mechanisme when getting the Ctrl-Close event that is processed the same as a SIGTERM.

close a socket port on linux [duplicate]

I am using Socket communication in one of my Java applications.As I know if the program meets any abnormal termination the listening ports does not get closed and the program cannot be started back because it reports "Port already open.."
Do I have anyway to handle this problem? What is the general way used to handle this matter?
It sounds like your program is listening on a socket. Normally, when your program exits the OS closes all sockets that might be open (including listening sockets). However, for listening sockets the OS normally reserves the port for some time (several minutes) after your program exits so it can handle any outstanding connection attempts. You may notice that if you shut down your program abnormally, then come back some time later it will start up just fine.
If you want to avoid this delay time, you can use setsockopt() to configure the socket with the SO_REUSEADDR option. This tells the OS that you know it's OK to reuse the same address, and you won't run into this problem.
You can set this option in Java by using the ServerSocket.setReuseAddress(true) method.
You want to set the SO_REUSEADDR flag on the socket.
See setReuseAddress().
The operating system should handle things such as that automatically, when the JVM process has ended. There might be a short delay before the port is closed, though.
As mentioned in the Handling abnormal Java program exits, you could setup a Runtime.addShutdownHook() method to deals with any special case, if it really needs an explicit operation.

Any Shutdown Hook when application is "Force Closed"?

Is there any way to make the program go through the shutdown hook if the user forces java to close (through the task manager or by closing the corresponding batch file).
My program currently runs and executes well, if the user closes the GUI then it goes through a set of steps to disconnect from the database. However, if the user closes the Java or the batch file (running side by side with the GUI) then the connection to the database isn't closed.
Is it possible to somehow force the connection closed and maybe even delete something from the tables? The batch file will probably not be an issue when I jar the program but the process killing still will.
Nope.
The shutdown hook will react to Ctrl+C, normal closes, user logouts, and normal system shut downs (which request a graceful shutdown of all applications).
However, if someone is force-closing the app it's assumed that that's what you actually want - immediate termination with no further notice. This question has been asked many times, and is confused by the behavior of many applications that, when they are asked to force-close, they actually take a long time to finally terminate. This is because in the OS's efforts to release all resources, some resources (especially certain I/O and/or file resources) don't let go immediately.
In testing an app that starts, and is intended to be running until a graceful shutdown (e.g. server software) you should run it at the console/command-line, and press Ctrl+C to stop the program (which will run the shutdown hook) rather than using Task Manager, or KILL -9.
Furthermore, there's nothing Java could even do about it if it wanted to. A force-close happens at the OS level, at which point it releases the memory, file and I/O handles in use, etc. Java does not (nor does any other program) have control over a force-close. At this point, the OS is taking charge.

Is it possible to know if a process is waiting in Blocked state on a Receive() call on Linux?

My main purpose is to execute processes one by one in a round-robin fashion until one calls receive() and is blocked, so that the execution switches to the next process in the queue. There is a controller application which is coded in Java and it executes these processes(which are also Java applications) using Runtime.getRuntime().exec() and keeps the return values which are Process objects.
To achieve this purpose, I need to capture the receive() calls(or their states, which is blocked) and tell them to the controller(master) application.
I can go as low-level as you want if this is possible.. My first thought was to get this information from the driver and then tell it to my controller Java application. I have written a linux kernel network module which captures the send and receive operations, but AFAIK the socket.receive() function does not tell anything to the network driver.
So, I think the options are to get this information from either the JVM, somehow get it from a linux command or so, or possibly through the linux kernel module?
What are your suggestions?
If you want to know if your threads are blocked, or exactly what they are blocked on, you can either take a thread dump or use a tool like jvisualvm to attach to the process and take a look (in jvisualvm you would attach to the process, take a thread dump, and then look at the activity of each thread).
Have you looked at systemtap? Should be readily available on recent Fedora systems.
Best
Anders
I don't know if this will help you, but you could get information about the state of a Java thread on your machine using local attach.
1) Add the tools.jar to your classpath and use VirtualMachine.list() to get a list of the running JVM on you machine.
2) Attach to the JVM processed using VirtualMachine.attach(virtualMachineDescriptor)
3) Get the local connector address, vm.getAgentProperties().get("com.sun.management.jmxremote.localConnectorAddress");
4) Use JMXConnectorFactory.newJMXConnector(...) to connect to the JVM
5) From the JMX connection lookup up the ThreadMXBean
6) From the ThreadMXBean you get an array of ThreadInfos that describes all threads in the JVM.
7) From TheadInfo#getThreadState() you can check if the state is ThreadState.BLOCKED
You should use interprocess communication primitives in your worker processes to notify the controller application that they are ready to receive data.
You can't make assumptions about how the child processes implement their socket read. They could be using recv, or select, or poll, etc., to wait for network data.
There are actually a few points here. The Linux scheduler is smart enough to pre-empt a blocked task. Meaning, if you call receive() and there's nothing waiting to receive, your task will probably be put to sleep until such a time that the call will return. You don't need to handle the scheduling; the Linux kernel will do it for you.
That said, if you need to know whether your task is blocked from some daemon application, if you're willing to write an LKM, why not just get the task in the task list that you're interested in, and check its state?
Of course, simply checking the state of the task might not tell you exactly what you want. If your task state is TASK_INTERRUPTIBLE, it only tells you that your task is waiting on something, but it might not be a trivial matter to figure out what that something is. Similarly, your task can be in a TASK_RUNNING state and not actually be running on the CPU at the current moment (but, at least, in the TASK_RUNNING state you know your task isn't blocked).
You can just send a QUIT signal (Ctrl-\ on the console) to get a thread dump.

Categories

Resources