IT.en_US/Apps

JSP code making Out Of Memory Error

동구멍폴로 2023. 2. 14. 23:37
반응형

Not FOR PRODUCTION !!!!!!!!

 

1. A sample JSP code that can lead to an OutOfMemoryError by allocating too many objects in memory

<%@ page import="java.util.*" %>

<html>
  <head>
    <title>Memory Error JSP</title>
  </head>
  <body>
    <h1>Memory Error JSP</h1>
    <%
      // Allocate too many objects
      List<String> list = new ArrayList<String>();
      while (true) {
        list.add("Out of Memory!");
      }
    %>
  </body>
</html>

This JSP page imports the java.util.* package and defines a simple HTML page with a title and header.

- Inside the <% %> block, a List object is created and an infinite loop is started to add new elements to the list.

  Because the loop will never terminate, the list will continue to grow until it consumes all available memory and triggers an OutOfMemoryError.

 

 When this JSP page is executed, it will eventually lead to an OutOfMemoryError due to excessive memory allocation. 

 

2. A sample JSP code that can cause an OutOfMemoryError by creating a large number of objects

<%@ page import="java.util.ArrayList" %>
<%
    ArrayList<String> list = new ArrayList<>();
    for (int i = 0; i < 100000000; i++) {
        list.add("object " + i);
    }
%>

 In this code, we are creating an ArrayList and adding 100 million objects to it in a loop.

- This will consume a large amount of memory and may eventually cause an OutOfMemoryError if the JVM runs out of memory.

 When this JSP page is executed, the server will attempt to allocate memory for the ArrayList and its contents.

If the JVM does not have enough memory to allocate, it will throw an OutOfMemoryError.

 

3. A sample JSP code that can cause an OutOfMemoryError in a Java web application using byte size

<%@ page import="java.util.ArrayList" %>
<%
  ArrayList<byte[]> list = new ArrayList<byte[]>();
  while (true) {
    list.add(new byte[1000000]);
  }
%>

 

 This JSP code creates an ArrayList of byte arrays and then adds new byte arrays to the list in an infinite loop.

- Since each byte array is one million bytes in size, this code will quickly consume all available memory on the server and cause an OutOfMemoryError to be thrown.

- 1000000 can be modified for JVM Heap memory value. (if heap is set 1024M, set 1,610,612,736 (1.5G) )

반응형

'IT.en_US > Apps' 카테고리의 다른 글

How to make a spring boot Application for testing  (0) 2023.02.13