I encountered a problem when I deploy a war to a cloud server(PasS,128Mb), and then I have two timers in my application.
Timer1
will be executing a task to log my memory(as well as a Map described in #2) every one hour.- Every time I create a Room object, I put this room into a Map, so I have a
Timer2
to create a task when I initiate a Roomto remove that object from a map.
I happen to know that that I should not use a timer.
But the problem is that I check the log logged by Timer1, my freeMemory
is going down every hour and the total memory is the same.
I have read What are Runtime.getRuntime().totalMemory() and freeMemory()?, so I know what the total memory and freeMemory means. And according to the log, my used memory is going up!
PS: I do NOT use any new Runnable or Thread to handle any long-running logic.
Logs are like:
2014-07-22 04:39:27 [ Timer-10:44100005 ] - [ INFO ]
maxMemory()=128
totalMemory() = 75
freeMemory()= 44
2014-07-22 04:39:27 [ Timer-10:44100005 ] - [ INFO ] Now there are Existing Room of : 0
2014-07-22 05:39:27 [ Timer-10:47700005 ] - [ INFO ]
maxMemory()=128
totalMemory() = 75
freeMemory()= 41
2014-07-22 05:39:27 [ Timer-10:47700005 ] - [ INFO ] Now there are Existing Room of : 0
2014-07-22 06:39:27 [ Timer-10:51300006 ] - [ INFO ]
maxMemory()=128
totalMemory() = 75
freeMemory()= 39
I am logging every time when this sevlet receive a request, so I am sure that no requests is handed,but why free memory going down.
1.This is how Timer1 works:
@Override
public void init() throws ServletException {
super.init();
LogUtil.info("CoreServlet inits");
memoryTimer=new Timer(true);
//check the memory every 1 hour,first time will be delayed to 15 mins later
memoryTimer.schedule(new checkMemoryTask(),TimeConstant.FIFTHTEEN_MINUTES_MILISECONDS,TimeConstant.ONE_HOUR_MILISECONDS);
commandService = CommandService.getInstance();
}
2.This is how Timer2 works.
public Room newRoom() {
Integer randomNumObject;
LogUtil.debug("Trying to new a room with the random number");
//generate a random number util the number is not a existing room number
do {
randomNumObject=generateRandom(4);//4 digits room number
} while (roomMap.containsKey(randomNumObject));//roomNum is existing, continue to find
Room newRoom=new Room(randomNumObject);//use this number to create a new room
roomMap.put(randomNumObject, newRoom);
//abandon the room after 15 MINTES
roomClearTimer.schedule(new abandonRoomTask(randomNumObject.intValue()), TimeConstant.FIFTHTEEN_MINUTES_MILISECONDS);
LogUtil.info(newRoom+" is scheduled to be abandoned 15 MINUTES later");
return newRoom;
}