Do you know how much memory it uses when you run it locally?
Increasing the size of the instance is not generally the best approach. For example, if you have a memory leak, then the instance size might need to grow exponentially!!
You can use Cloud Code to help you debug these types of situations. You can also use the Cloud Profiler for Java to understand better what your code is consuming.
I am more familiar with Python than Java, but I wonder how you are implementing the Java code? Looping in Python is notoriously problematic as it has a habit of leaving behind and accumulating "garbage" in memory. You can implement List Comprehensions, Generators, and Yield returns in Python to consume memory more efficiently. I have added a link that explains my thinking better and provides a helpful comparison. I believe that you can do something similar in Java, but I might be wrong. You can also try chunking your data, but you might be limited in how you can split your data, so it might not be the best fit.