Memory pressure testing with Epsilon

Imagine that you don't want your application, or say, a section of your application, to use more than a certain amount of heap memory, such as 40 MB. How can you assert this? In this case, you can configure to execute your applications with -Xmx40m. Here's some example code that adds the same string values as the key/value pair to HashMap and then removes itby iterating it multiple times (1_000_000 to be precise):

import java.util.*; 
class EpMap { 
    public static void main(String args[]) { 
        Map<String, String> myMap = new HashMap<String, String>(); 
        int size = 1_000_000; 
        for(int i = 0; i < size; i++) { 
            String java = new String("Java"); 
            String eJavaGuru = new String("eJavaGuru.com"); 
            myMap.put(java, eJavaGuru); 
            myMap.remove(java); 
        } 
    } 
} 

You can execute it using the following command:

    > java -XX:+UnlockExperimentalVMOptions -XX:+UseEpsilonGC -Xlog:gc* 
-Xmx40M EpMap

The preceding code exits with OutOfMemoryError, as shown in the following screenshot:

Let's revisit the code that generated this output and check whether we can do something about it. At present, the code uses the new operator to create the same string values. Let's see what happens if I modify it to use the string pool, as follows:

import java.util.*; 
class EpMap { 
    public static void main(String args[]) { 
        Map<String, String> myMap = new HashMap<String, String>(); 
        int size = 1_000_000; 
        for(int i = 0; i < size; i++) { 
            String java = "Java";
String eJavaGuru = "eJavaGuru.com"; myMap.put(java, eJavaGuru); myMap.remove(java); } } }

On the execution of this modified code, try executing the following command:

    > java -XX:+UnlockExperimentalVMOptions -XX:+UseEpsilonGC -Xlog:gc* 
-Xmx40M EpMap

The preceding code doesn't exit with OutOfMemoryError and completes the execution, as demonstrated in the following screenshot:

Reducing garbage is just one of the solutions to out of memory errors. To prevent or delay a GC cycle, you can also tune your runtime using multiple parameterssuch as increasing the heap size or by setting a minimum time before a GC cycle runs.

This brings me to a very interesting case; can you design a garbage-free application, that is, one that can work with Epsilon forever? I think we already have a few that are in production and are in use by developers (as covered in the next section).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.123.34