Multiple app instance logging - java

My application is allowed to have multiple instances running and I would like to log events from all running instances. I am currently using java util logging's socket handler to centralize the logging process. When the first instance starts, it also a starts a new socket server thread. The problem is when this instance is closed, the server thread is also closed and log method (from another instance) throws exception. I am not thinking to run it as a separate process (using Runtime exec) because I would not be able to shut it down gracefully from my application.
So is there a way where another instance on seeing the server down, create a new server thread? This similar approach is being done in H2 database AUTO_SERVER mode where it automatically switches to client and server mode.
So any suggestions on how to do this?

I ended up using Logback's prudent mode.

I think that you might need a singleton with a factory method to initialize the socket server if it is not already running:

Related

How to shutdown java application? [duplicate]

I'm interested in different approaches to gracefully shutting down a Java command line program. Sending a kill signal is not an option.
I can think of a few different approaches.
Open a port and wait for a connection. When one is made, gracefully shutdown.
Watch for a file to be created, then shutdown.
Read some input from the terminal, such as "execute shutdown".
The third one is not ideal, since there is often program output pumped to the screen. The first one takes too much effort (I'm lazy). Do most programmers use the second option? If not, what else is possible/elegant/simple?
you can try something like this:
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() { /*
my shutdown code here
*/ }
});
edit:
the shutdown hook will not perform the shutting down of the app. instead, it gives the developer a way to perform any clean-up that he/she wishes at shutdown.
from the JavaDoc for Runtime (a good read if you are planning to use this method):
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. ...
you could try to use Runtime.getRuntime().addShutdownHook() that should satisfy your requisite. In this way you can register an hook to do cleanups, in order to perfom a gracefull shutdown.
EDIT
http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Runtime.html#addShutdownHook(java.lang.Thread)
public void addShutdownHook(Thread hook)
Registers a new virtual-machine shutdown hook.
The Java virtual machine shuts down in response to two kinds of events:
The program exits normally, when the last non-daemon thread exits or when the exit (equivalently, System.exit) method is invoked, or
The virtual machine is terminated in response to a user interrupt, such as typing ^C, or a system-wide event, such as user logoff or system shutdown.
The benefit of the second option - checking for a file - over the first - listening on a port - is that you have some possibility of security.
You can set the permissions on the directory where the file is created so that only appropriate users can close the program. If you listen on a port any user can connect to it.
If you wanted to go with the socket version, it is very simple to implement. Here's the code:
ServerSocket server = new ServerSocket(8080);
System.out.println("Socket listening!");
server.accept();
System.out.println("Connection received!");
You could easily embed this code in a separate thread that you start with your program, and then have it modify global state to initiate shutdown.
The first two option is simple to implement. You could also use some JMX stuff (I don't know much about that). Tomcat uses the first approach and I applied 1 and 2 in two of my projects.
Consider having a JMX component. Then you can attach with JConsole either locally or over the network, and communicate with your component. Then the component can shut down the program properly.
With Java 6 u 10 or later, you can do the same with JVisualVM.
I would suggest to use the shutdown hook. It will allow your program do be controlled using standard OS tools. It also does not need any additional access to external resources (disk, ports, whatever).

Need redirecting output from multi-threaded socket server to other clients.

What I have is a multi threaded socket server listening for clients. New thread is created and started for opened connections. Clients can ask a server to execute some commands via Runtime .exec() method. Any new command received is handled by new thread (with PrintWriter passed as a parameter) and all the output (std/err) is send over the socket with PrintWriter.
The problem is that when the command takes longer (i.e. daemon) and the client disconnects for any reason I can't get the output anymore. I need to find a way of getting the output from that command execution thread on another connection (new client session which will be on another thread).
I could try to send all the output from commands to System.out and try to send it (System.out) over socket with PrintWriter (I don't know how to do this). And if I'm sucessfull maybe there is a way of sending all the such an output to every connected clients.
But then, I'm saving all the output to the database and in case of multiple clients connected I would end up having multiple inputs in my database.
Please give me some ideas as how I could go about with this issue. Thanks
You probably want to make your calls asynchronous. Executing tasks of unknown duration should never be made synchronously.
I would consider using a "reactor"-type server (i.e.: one thread per client = quick death) and using some type of message passing mechanism for long running transactions. There are a lot of middlewares that do this kind of work, it really depends on what platform you're on.
By the way, using a socket connection to execute command on a remote machine is a security flaw, but you probably already know that!
So, did you consider using a session ID for each connection? This ID will be associated with the output of each execution. So the same output could be retrieved on a subsequent call from the same user. Temporarily, the output could be stored at a repository (e.g. DB, memory, file).
Please correct me if I am not getting your question properly.

Stream closed before the program finishes [duplicate]

This question already has an answer here:
Using special auto start servlet to initialize on startup and share application data
(1 answer)
Closed 7 years ago.
I am using jetty server to receive calls from http clients.
I am using BufferedWriter object to write a log file for debugging.
The server is always running in order to receive calls.
How can i tell the program to only close the stream (log_file.close) when the server stops?
I am not supposed to stop the server, but before the program terminates (when i touch the terminate button for example) how can i close the stream file in that point?
If your code is running inside a web application (aka war) you can (and it's actually a best practice) to implement ServletContextListener and register it in your web.xml.
In contextInitialized you can make the necessary init operations.
In contextDestroyed you can close the stream.
If you are running Jetty embedded, then you have a couple of options.
You haven't indicated which version of Jetty, so I can't give you exact code for it, but your options are:
Register a "LifeCycle" object in the server, and implement a stop method in that lifecycle object that closes your log file. (Using something like addLifeCycle or addBean, depending on your Jetty version)
Add a shutdown thread in the JVM (Runtime.addShutdownHook)

How to integrate memcached in a Servlet? Tomcat & memory leaks

Searching memcached java in google, the first result is Using Memcached with Java.
The guy (who calls himself Just some Random Asshole in the Internet!) proposes a Singleton based on net.spy.memcached. It basically creates 20 threads and connections by creating 20 instances of MemcachedClient. For every request it chooses one at random.
However those threads and connections are never closed and they pile up every time I hot swap the application during development (with warnings from Tomcat 7).
SEVERE: The web application [/MyAppName] appears to have started a thread named
[...] but has failed to stop it. This is very likely to create a memory leak.
By looking at MemcachedClient JavaDoc, I see a method called shutdown with the only description being "Shut down immediately." Shut down what? The client? The server? I suppose is the client, since it's in MemcachedClient and I suppose that this method would close the connection and terminate the thread. EDIT: yes, it shuts down the client.
Question 1 How to force the execution of cleanup code in Tomcat 7, before the application is hot swapped?
Question 2 Is this approach of using memcached (with cleanup code), correct or is better I start over in a different way?
I think creating 20 memcache clients is silly - that's like creating 20 separate copies of your DB connection pool. The idea with that client is that it multiplexes a variety of requests with asynch IO.
http://code.google.com/p/spymemcached/wiki/Optimizations
As far as shutting it down, simply call:
yourClient.shutdown() to shutdown immediately, or
yourClient.shutdown(3, TimeUnit.SECONDS) for example, to allow some time for a more graceful shutdown.
That could be called from your Servlet's .destroy method, or a context listener for your whole WAR.
I don't know anything about memcached, but you could probably write a custom context listener and put some kind of shutdown hook in the context listener so that when the context shutdown you could loop through the items in your singleton and shut them down.
It turned out that it was a bug of Java AWS SDK and was not related to memcached. Version 1.2.2 of Java AWS SDK has this bug fixed.

Starting and reconnecting to a spring bean from console

I like to write a little server application being controlled by a little console app (start, pause, stop, etc). For the server spring should be used (part of it already exist). So what I do to start the server is something like this:
start a server thread and exit main method
and then, in the thread:
load application context from xml
start some worker threads connecting to beans doing stuff
Now I want the server to be stopped by another command. How can I connect to the already running context and shut it down?
Thanks for your help,
Alexander
The classical way to manage running Java code is through JMX.
Spring lets you export beans as MBeans.
And for accessing JMX via the command line, look at the answers to this recent question:
Calling JMX MBean method from a shell script
You could create a pid file, when the server starts, it should log the pid to a file, server.pid. When you do a stop, you can read the process and kill it. Or even simpler, have a ever running thread in your main class which keeps looking for a file in some folder. As soon as the file becomes available or gets modified, it will stop the server.

Categories