I have a simple Java server application implemented using com.sun.net.HttpServer
API. It receives REST requests almost every second, reads a large HashMap
for some texts and simply sends back the texts after some processing. The server part simply looks like this:
public class Server implements Runnable {
static final Logger logger = LogManager.getLogger(Server.class);
static int serverPort = 9002;
HttpServer server;
public Server() {
Thread t = new Thread(this);
t.start();
}
public void run() {
try {
server = HttpServer.create(new InetSocketAddress(serverPort), 0);
logger.info("EventRetriever REST server listening to port: " + serverPort);
server.createContext("/getEvents", new MedatadaHandler());
server.setExecutor(null);
server.start();
} catch (IOException e) {
logger.error(e);
}
}
class MedatadaHandler implements HttpHandler {
@Override
public void handle(HttpExchange he) throws IOException {
//...
String response = requestEvents();
he.sendResponseHeaders(200, response.length());
OutputStream os = he.getResponseBody();
os.write(response.toString().getBytes());
os.close();
}
}
//some other functions...
public String requestEvents(){
//read from a HashMap, some processing, creating a JSON and sends it while logging it in file
logger.info(jsonString);
return jsonString;
}
}
}
While running as a docker container, I see the memory usage increases over time, like an average of few MB
over few seconds. Apparently, somewhere here we have a memory leak. Is it the unused objects, the j4logger
loggings, or whatnot, I don't really know. I just tried to call a System.gc()
explicitly once every few minutes. It does some remedy, but I am not sure where the problem is coming from.
What is the problem and how to fix it?
EDIT: how do I know the problem is coming from this part of program? Well, I have other thread responsible for filling those HashMaps
every 5 mins, then going to sleep. Even when that's on sleep, I see memory increase. The only part is this server which is serving every second.