Skip to content

Commit

Permalink
Add option to control whether a JRest server will try to keep the app…
Browse files Browse the repository at this point in the history
…lication alive.
  • Loading branch information
orange451 committed Mar 24, 2022
1 parent 1cf7f6e commit b5a11fe
Showing 1 changed file with 29 additions and 3 deletions.
32 changes: 29 additions & 3 deletions src/main/java/io/jrest/JRest.java
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,9 @@ public class JRest {
/** Port the server is running on **/
private int port;

/** Whether the JREST server will keep the application alive if no other NON-DAEMON threads are running **/
private boolean keepApplicationAlive;

/** Client use of cookies **/
protected static CookieManager cookieManager;

Expand All @@ -66,6 +69,7 @@ public class JRest {
/** Use {@link JRest#create()} to create a new JRest instance **/
private JRest() {
this.port = 80;
this.keepApplicationAlive = true;
this.logger = new Logger();
this.endpointMap = new HashMap<>();
this.responseHandlerMap = new HashMap<>();
Expand Down Expand Up @@ -104,7 +108,7 @@ public JRest start() {

// Server initializing
if ( server != null ) {
this.getLogger().error("Server is already started on port: " + port);
this.getLogger().error("Server is already started on port: " + server.getLocalPort());
return this;
}

Expand All @@ -120,7 +124,9 @@ public JRest start() {
initializing = true;

// Start new server
new JRestServer().start();
Thread t = new JRestServer();
t.setDaemon(!getKeepApplicationAlive());
t.start();

// Wait for server to turn on
while (!error && initializing) {
Expand Down Expand Up @@ -148,7 +154,7 @@ class JRestServer extends Thread implements Runnable {

public void run() {
try {
server = new ServerSocket(port);
server = new ServerSocket(getPort());
server.setSoTimeout(0);

long elaspedTime = System.currentTimeMillis()-startTime;
Expand Down Expand Up @@ -459,6 +465,26 @@ public JRest setPort(int port) {
return this;
}

/**
* Get whether the application will stay alive if no other non-daemon threads are running.
*/
public boolean getKeepApplicationAlive() {
return this.keepApplicationAlive;
}

/**
* Set whether the application will stay alive if no other non-daemon threads are running.
*/
public JRest setKeepApplicationAlive(boolean keepApplicationAlive) {
if ( started || server != null ) {
this.getLogger().error("KeepApplicationAlive cannot be specified on a server that is starting or has been started.");
return this;
}

this.keepApplicationAlive = keepApplicationAlive;
return this;
}

/**
* Return the session storage used for this JREST server.
*/
Expand Down

0 comments on commit b5a11fe

Please sign in to comment.