Java Memory Leak Test

Source: Internet
Author: User



1. We know that when an object is created, the memory that is opened to the object is on the heap, and if the object is large enough, or if the object is big enough, it causes heap overflow when the heap memory is not allocated.

2. We know that variables of value types are stored in the stack space, and if the value type variable is large enough it will cause the stack to overflow, and we also know that the recursive invocation of the function will also be pushed to the stack operation.

3. Below we write a small program to test if you use heap and stack overflow.

Package Com.dangdang
Import Java.util.arraylist;import Java.util.list;public class Memoryleak {public static void main (string[] args) throw        s Exception {char input;        System.out.println ("Input 1 to test Heap_memory_leak, others to test Stack_memory_lead");        input = (char) System.in.read ();            if (' 1 ' = = input) {System.out.println ("began to test Heap memory leak!"); New Memoryleak (). New MyMemory ().        Heapleaktest (); } else{new Memoryleak (). New MyMemory ().        Stackleaktest ();        }} class Mymemory{public MyMemory () {}///The objects are stored in Heap            public void Heapleaktest () {list<int[]> intlist = new arraylist<int[]> ();                while (true) {int[] Leakint = new int[10000000];            Intlist.add (Leakint);         }}//Recursion'll do push stack action public void Stackleaktest () {   Stackleaktest (); }    }}

4. Test Results

Heap Overflow

Exception in thread "main" Java.lang.OutOfMemoryError:Java heap space

At Com.dangdang.memoryleak$mymemory.heapleaktest (memoryleak.java:27)

At Com.dangdang.MemoryLeak.main (memoryleak.java:12)

Stack Overflow

Exception in thread "main" Java.lang.StackOverflowError

At Com.dangdang.memoryleak$mymemory.stackleaktest (memoryleak.java:34)

At Com.dangdang.memoryleak$mymemory.stackleaktest (memoryleak.java:34)

.....


-------migrated from personal space------

Java Memory Leak Test

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.