Consider a java process, in that the main thread reads Json objects from a source and assigns a task with the read Json objects to a FixedThreadPoolExecutor with 5 worker threads.
Here the problem is, the source from which the Jsons are read is much faster than the completion of the tasks by the worker thread. So, as the Jsons accumulate in memory waiting for the worker threads, OutOfMemoryException is thrown. Here the number of worker threads cannot be increased.
So will the following be an efficient solution to this OutOfMemory problem?
In main thread check the percent of available memory and sleep for some time if the memory usage is more than 80%
main(){
for(;;){
//read the data and assign to executor
long total = Runtime.getRuntime().maxMemory(),free = Runtime.getRuntime().freeMemory()
float usedPersent = (total-free)*100/total
if(usedPercent > 80)
Thread.sleep(2000);
}
}
Will there a good practice?