Need a solution for Java Method which returns a string Value to be executed only n number of threads in JVM

Java Method which returns string(fileName) is consuming memory internally for few Image operations which cannot be further optimized, lets say consuming 20 MB HeapSpace per method execution.

This method is executing as part of ProcessingImageData and need to return the file name as output to RestWebService caller.

While some n threads are parallel processing which is giving OutofMemory.

To escape from OutofMemory-HeapSpace can you please provide your suggestions like setting only fixed number of threads to execute this method.

public String deleteImageAndProvideFile(String inputImage, int deletePageNum){
        // process image
        //find page and delete
        //merge pages to new file
        // return new file Name
}

Upvotes: 0

Views: 42

Answers (1)

Stephen C
Stephen C

Reputation: 719199

If you have an number of tasks but you want to limit the number of threads performing them, use an ExecutorService with a bounded thread pool.

The Executors class has a helper method for creating what you need:

  • newFixedThreadPool(int nosThreads) (javadoc).

Adjust the nosThreads parameter according to how much memory you want to use.

The ExecutionService documentation explains how to use the API (javadoc). You submit tasks and get Future objects that can be used to wait until a given task is finished.

In your use-case, one of your web requests might submit task to a "global" executor service and then wait for the task to complete. Alternatively you could design your system so that the processing is done asynchronously with the web requests; e.g. submit a task in one request, and then make another request to see if it has been done yet.

Upvotes: 1

Related Questions