Running Java Programs in the Background
Running a Java program in the background is crucial for keeping applications or services active even after terminal sessions end. This article covers multiple techniques to run Java programs as background processes in Linux and other Unix-like systems.
1. Create a Simple Application
We will start by creating a minimal Java web server using Jetty Embedded.
public class JettyServer { private static final Logger LOGGER = Logger.getLogger(JettyServer.class.getName()); public static void main(String[] args) throws Exception { Server server = new Server(8080); ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS); context.setContextPath("/"); server.setHandler(context); context.addServlet(HelloServlet.class, "/hello"); LOGGER.info("Starting Jetty server on port 8080..."); server.start(); LOGGER.info("Jetty server started successfully."); server.join(); } public static class HelloServlet extends HttpServlet { private static final Logger LOGGER = Logger.getLogger(HelloServlet.class.getName()); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { LOGGER.info("Received request: " + req.getRequestURI()); resp.setContentType("text/plain"); resp.getWriter().write("Hello, world from Jetty!"); } } }
Assuming your are using Maven, to build the application, run the command mvn clean package
from the project root directory. In case you are using a different build system, build an executable jar archive for your project. This packages the application into a JAR file. Upon successful completion, the generated JAR file will be located in the target
directory with the name jetty-background-1.0.jar
, ready to be executed or deployed.
2. Running the Java Program in the Background
Now let’s explore different methods to run the Java process in the background.
2.1 Using &
and Redirect Output
When you run a Java program from the terminal, appending an ampersand (&
) allows the process to continue running in the background, freeing up the terminal for other tasks. To prevent the program’s output from cluttering the terminal or being lost, you can redirect both standard output and error streams to log files. This method is simple and effective for lightweight applications or during development.
java -jar target/jetty-background-1.0.jar > output.log 2>&1 & echo $! > jettyServer.pid
The command java -jar target/jetty-background-1.0.jar > output.log 2>&1 &
runs the Java application from the specified JAR file in the background, redirecting standard output to output.log
and also redirecting standard error (using 2>&1
) to the same file, ensuring all logs and errors are captured while the terminal remains available for other commands.
java -jar target/jetty-background-1.0.jar
: Runs the Java application packaged in your JAR file.>
: Redirects standard output (stdout) to a file.output.log
: The file where both normal output and error messages will go.2>&1
: Redirects standard error (stderr) to the same place as standard output (i.e.,output.log
).&
(at the end): Runs the command in the background, allowing your terminal to remain free.
Note: Closing the terminal will stop the process unless you use nohup
to detach it from the terminal session.
2.2 Using nohup
(No Hangup)
The nohup
command allows you to run a process in the background even if the terminal session is closed. It stands for “No Hangup,” which means it prevents the process from being terminated when the terminal session ends. This is useful for long-running applications or servers that need to continue running after logging out or closing the terminal.
nohup java -jar target/jetty-background.jar > output.log 2>&1 &
nohup
: Allows the process to keep running even after the terminal is closed.- The
output.log
will store the output.
This is the most commonly used method for long-running background processes.
2.3 Using screen
Session
The screen
command allows you to create a detachable terminal session, making it ideal for running long-lived processes like Java applications. With screen
, you can start your application in a virtual terminal, detach from it, and later reconnect, even after closing your terminal window. This is especially useful on remote servers or when managing multiple background processes interactively.
screen -S jetty-server
Inside the new screen session:
java -jar target/jetty-background-1.0.jar
To detach from the session:
- Press
Ctrl+A
, thenD
.
To resume the session later:
screen -r jetty-server
screen
is ideal for debugging and monitoring background services, providing persistent access to terminal output even after disconnection.
2.4 Using tmux
Session
tmux
is a terminal multiplexer that lets you run multiple terminal sessions within a single window and detach from them at any time. It is an alternative to screen
for managing long-running background applications. With tmux
, you can start your Java program, detach the session, and later reattach to continue monitoring or interacting with the process, even after closing your terminal
tmux new -s jettyserver
This creates a new session named jettyserver
. Next, run your Java program inside tmux
:
java -jar target/jetty-background-1.0.jar
Detach from session:
- Press
Ctrl+B
, thenD
. This detaches the session but leaves your Java app running.
Reattach the session later:
tmux attach -t jettyserver
List all sessions:
tmux ls
Kill a session:
tmux kill-session -t jettyserver
Similar to screen
, but designed to be more modern, flexible, and user-friendly, tmux
offers enhanced features such as easier session management and better scripting support.
2.5 Running with a Shell Script
Creating a shell script to start your Java program in the background is a convenient way to automate the launch process, especially during deployment or system startup. The script can include commands for logging output, storing the process ID (PID), and ensuring the application runs detached from the terminal.
You can create a script run-server.sh
:
#!/bin/bash nohup java -jar target/jetty-background-1.0.jar > output.log 2>&1 & echo $! > jetty.pid echo "Jetty server started in background with PID $(cat jetty.pid)"
Make it executable:
chmod +x run-server.sh ./run-server.sh
While running your Java program with a shell script is convenient, it is not always the best choice for production environments. Shell scripts offer limited error handling, lack robust monitoring, and do not automatically restart the application if it crashes.
3. Stopping the Background Process
Once your Java application is running in the background, you will eventually need to stop it gracefully. This is typically done by identifying the process ID (PID) of the running application and then terminating it using a standard kill
command. Managing processes this way helps ensure resources are released properly and avoids leaving orphaned processes running on your system.
You can use the jps -l
command, which is part of the JDK (Java Development Kit), to list all active Java processes along with their fully qualified class names or JAR file names. This is useful for identifying Java applications when you don’t know their exact process ID.
jps -l
Example output:
In this output, 11063
is the process ID (PID) of the background Java application (
). You can use this PID to manage or stop the process as needed.
target/jetty-background-1.0.jar
4. Conclusion
In this article, we covered effective ways to run Java programs in the background, focusing on tools available on Unix-based systems. Whether through output redirection, nohup
, or terminal session tools like screen
and tmux
, these methods can help ensure your applications continue to run even after you disconnect. For more reliability in production, however, it is worth exploring managed services or system-level tools.
5. Download the Source Code
This article covered how to run a Java program in the background.
You can download the full source code of this example here: java program background