What is MetaSpace in Java?


"MetaSpace" is not a phrase that is generally used or recognised as part of the Java Programming language’s standard library or syntax. As a result, "MetaSpace" is likely to relate to anything specific to a particular Java programme or project, rather than a general Java idea.

It is impossible to offer a detailed description or explanation of "MetaSpace" in Java without further context or infformation about the individual application or project. However, it’s possible that "MetaSpace" refers to thhe physical world rather than the digital or virtual world. It may be used in this context to distinguish between online or wirtual interactions and in-person interactions.

How to use MetaSpace in Java?

MetaSpace is a new memory space introduceed in Java 8 to replace the previous version’s Permanent Generation (PermGen) space. The MetaSpace is used to hold class metadata and is meant to dynamically resize based on the application’s demands.

Here, how to use MataSpace in Java −

  • If optimizing your Java program's performance is crucial for achieving successful outcomes, considering configuration with respect to utilizing MetaSpace is a worthy approach. The XX:Meta SpaceSize &XX: MaxMeta SpaceSize JVM option facilitate this customization process.

    Specifically, employing commandline arguments lets developers assign preliminary or upper limits towards Memory Management features - for example - suggesting an initial capacity of 256 MB alongside a maximum threshold value of up to 512 MB, tailored according to demand.

    java -XX:MetaspaceSize=256m -XX:MaxMetaspaceSize=512m MyApp

  • Monitor MetaSpace usage − JMX (Java Management Extensions) may be used to monitor MetaSpace utilisation in real time. The MBean "java.lang:type=MemoryPool,name=Metaspace" offers the following characteristics for monitoring MetaSpace usage −

    • usage − current usage of MetaSpace

    • peakUsage − peak usage of MetaSpace

    • maxUsage − maximum size of MetaSpace

Example

Here, an example of how to use JMX to monitor MetaSpace usage in Java code −

import java.lang.management.ManagementFactory;
import java.lang.management.MemoryPoolMXBean;

public class MetaspaceMonitor {
   public static void main(String[] args) throws Exception {
      MemoryPoolMXBean metaspaceBean = ManagementFactory.getMemoryPoolMXBean("java.lang:type=MemoryPool,name=Metaspace");
      while (true) {
         System.out.println("Metaspace used: " + metaspaceBean.getUsage().getUsed() / (1024 * 1024) + " MB");
         Thread.sleep(1000);
      }
   }
}
  • Tune MetaSpace performance − We can use the following JVM parameters to improve MetaSpace performance −

    • -XX:+UseConcMarkSweepGC: For MetaSpace, utilise the CMS trash collector.

    • -XX:+CMSClassUnloadingEnabled: enable CMS trash colletor class unloading

    • -XX:+UseCompressedClassPointers: MetaSpace’s memory use can be reduced by using compressed class references.

      Inorder to use MetaSpace in Java, we must first specify the MetaSpace size, then monitor MetaSpace utilisation and modify MetaSpace performance using suitable JVM parameters.

Algorithm of MetaSpace

  • The JVM reads the class defination and extracts metadata about the class, including as its name, parent class, interfaces implemented, fields and methods when a new class is loaded.

  • The JVM then allocates memory in the MetaSpace for the class’s metadata.

  • The JVM maintains track of the MetaSpace’s size as well as the amount of memory utilised by each class’s information.

  • If the quantity of metadata in the MetaSpace exceeds the allocated space, the JVM will initiate a Garbage Collection (GC) event to clear up space. This is referred to as a MetaSpace Garbage Collection (GC).

  • The JVM will detect all the metadata that is no longer is use and free up the related memory during a MetaSpace Garbage Collection (GC) event.

  • If the memory freed up by the MetaSpace to handle the additional metadata, the JVM will expand the MetaSpace.

  • If the quality of metadata in the MetaSpace remains consistent over time, the JVM may shrink the MetaSpace to save memory.

  • When a class is no longer is use or the JVM shuts down, the metadata in the MetaSpace is immediately emptied.

Approach in MetaSpace

  • Get the MetaSpace memory usage − We may use the following code to retrive the current utilisation of the MetaSpace memory space −

    • MemoryUsage metaspaceUsage = ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage();

    • long usedMetaspace = metaspaceUsage.getUsed();

    • long maxMetaspace = metaspaceUsage.getMax();

  • Increase the MetaSpace memory size − We may use the following command line option to raise the maximum size of the MetaSpace memory space −

    • -XX:MaxMetaspaceSize=

      Where is the maximum size of the Metaspace memory space in bytes.

  • Monitor MetaSpace memory usage − We monitor the MetaSpace usage runtime −

    • MemoryPoolMXBean metaspaceBean = ManagementFactory.getMemoryPoolMXBean("Metaspace");

    • MemoryUsage usage = metaspaceBean.getUsage();

    • long usedMetaspace = usage.getUsed();

    • long maxMetaspace = usage.getMax();

    • This code retrieves the MemoryPoolMXBean for the Metaspace memory pool and gets the current usage and maximum usage.

  • Reduce the MetaSpace memory usage − We reduse the MetaSpace memory usage −

    • Unload unnecessary classes and interfaces using the Class.unload() method.

    • Increase the size of the Metaspace memory space using the -XX:MaxMetaspaceSize command line option.

    • Tune the class loading behavior of the application to avoid loading unnecessary classes and interfaces.

Example

import java.lang.management.ManagementFactory;
import java.lang.management.MemoryPoolMXBean;

public class MetaspaceExample {
   public static void main(String[] args) {
      for (MemoryPoolMXBean pool : ManagementFactory.getMemoryPoolMXBeans()) {
         String name = pool.getName();
         if (name.contains("Metaspace")) {
            System.out.printf("%s: %d bytes\n", name, pool.getUsage().getUsed());
         }
      }
   }
}

Output

Metaspace: 696072 bytes

Conclusion

MetaSpace in Java is a consider advance over PermGen speace, delivering superior speed, stability and scalability for JVM based applications. It is an important componant of contemporary Java versions and develpers should be aware of its use to optimise the memory utilisation of their programmes.

Updated on: 28-Jul-2023

691 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements