Question

Java object lifecycle: Describe the lifecycle of the objects created within the method listed below. Discuss whether th...

Java object lifecycle:

Describe the lifecycle of the objects created within the method listed below. Discuss whether this program (assume that this method is embedded in a class) will fail with an out of memory error. And Explain when a stack overflow error can occur in Java, using an example program.

public static void main(String[] args) throwsException {

    java.util.Set set = new java.util.HashSet();

    while(set.size()>-1) {

        set = new java.util.HashSet();

        Thread.sleep(1000); // wait 1 s

        for (int i=0;i<1000000;i++) {

            set.add(newObject());

        }

    }

}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

stack Line1 stack Line3 Heap i-4 public void Method10 cls1(ref) { y-2 cls1 int i-4 Object stack Line2 i-4 int y 2 y 2 new cla

These errors occurs when program runs out of memory depending on the
available physical memory (RAM) for pc/laptop

Their are two parts of memory used by java programs.
1. stack memory
   It is used to store the variables and
   object referrences(which are also variables of class, Student s1's only address/reference not data).
  
2. heap memory
   It is used to store object's data into memory (student name, roll, grade
   or int i j k... variables in object for each object).
   if object holds more instance variables/fields then it needs more memory per object.
-------------------------------------------
Ans 1. This program will not fail with out of memory error because
   look the code in while loop,
  
   while(set.size()>-1) {
set = new java.util.HashSet();   // create new hashset everytime (discarding old data)
//this causes to loose 1000000 objects added previously after 2nd time loop runs
//so set holds 1000000 objects maximum, thus it can store 1000000 objects easily(normally) and no error
//but if at any time in the system other processes/applications are using more memory
//causing our program to have less memory then out of memory error can occur due to heap memory shortage
  
Thread.sleep(1000); // wait 1 s
for (int i=0;i<1000000;i++) {   // add 1000000 objects to hashset
set.add(newObject());
}
}
-------------------------------------------
but if we comment/delete below line in while loop
//set = new java.util.HashSet();

then it will cause while loop to add 1000000 objects each time loop runs
so set's size grows(and also heap size), and eventually heap runs out of memory and gives error

to test this change program like this and see output
comment this //set = new java.util.HashSet();
System.out.println("Set size:" + set.size()); //to see the set size
Thread.sleep(10); // change sleep time to 10 to get output faster
---------------------


-------------------------------------------
Ans 2.
   Stack overflow error can occur mostly due to bad recursive call to function
   (function calling same function repeatedly).
  
   Because each time the function calls to itself program needs to store
   some data into stack memory such as
       method parameters, its local parameters, and the return address of the method
       and this needs some memory
   this causes stack to grow(reducing available stack memory further)
   and at some point stack runs out of memory and gives error by JVM

see the following example that cause stack error
  
//StackOverflowErrorExample.java
public class StackOverflowErrorExample {

public static void recursivePrint(int num) {
System.out.println("Number: " + num);

if(num == 0)   // this never occurs
return;   // function never returs and runs infinitly
else
recursivePrint(++num); // recursive call, as each time we call same function by increasing num by 1
}

public static void main(String[] args) {
StackOverflowErrorExample.recursivePrint(1);   // start from 1
}
}
  
-------------------------------------------
thank you...

// MemLoadTest.java gives heap error :)
public class MemLoadTest {
public static void main(String[] args) throws Exception {
java.util.Set set = new java.util.HashSet();
while(set.size()>-1) {
//~ set = new java.util.HashSet();
System.out.println("Set size:" + set.size());
Thread.sleep(10); // wait 10 ms
for (int i=0;i<1000000;i++) {
set.add(new Object());
}
}
}
}

stack Line1 stack Line3 Heap i-4 public void Method10 cls1(ref) { y-2 cls1 int i-4 Object stack Line2 i-4 int y 2 y 2 new class10): class1 cls1 i-4 exiting method Heap stack cls1 Object

Add a comment
Know the answer?
Add Answer to:
Java object lifecycle: Describe the lifecycle of the objects created within the method listed below. Discuss whether th...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Java - Object lifecycle and memory management Consider the following Java programs: Program Code publ ic cl ass A a pub...

    Java - Object lifecycle and memory management Consider the following Java programs: Program Code publ ic cl ass A a publ ic st at ic voi d mai n( St ri ngl1 args) t hr ows Excepti on whi I e (true) for (i nt i -0 ; i <1000000; i ++) Cbj ect obj new Obj ect ); gi ve JVM 100ms ti me to run gar bage col l ect i on Thr ead. sl eep( 100): i...

  • JAVA (advanced data structures) write a completed program using HashIntSet and HashMain include the method in the main...

    JAVA (advanced data structures) write a completed program using HashIntSet and HashMain include the method in the main if possible. those are just the sample HashIntSet and HashMain (don't have to be the same but follow the Q requirement. thanks HashIntSet.java public class HashIntSet { private static final double MAX_LOAD_FACTOR = 0.75; private HashEntry[] elementData; private int size; // Constructs an empty set. public HashIntSet() { elementData = new HashEntry[10]; size = 0; } // Adds the given element to...

  • Draw memory diagrams for all variables and objects created using during the execution of main method...

    Draw memory diagrams for all variables and objects created using during the execution of main method below: class Singleton {     private int value;     Singleton( int value ) {         this.value = value;     } } class Pair {     private Object first;     private Object second;     Pair( Object first, Object second ) {         this.first = first;         this.second = second;     } } public class Quiz {     public static void main( String[] args ) {         Singleton s;         Pair p1, p2;         s = new Singleton( 99 );...

  • JAVA I. Using the Event Class created previously, create an array of objects;        II. Demonstrate...

    JAVA I. Using the Event Class created previously, create an array of objects;        II. Demonstrate passing array reference to a method;        III. Demonstrate creating array of objects that prints out only x 0.0 for all objects. PROJECT 5C - ARRAYS Create a new file called " EventArray5C". There are some "challenging" directions in this project. . 1.Prepare a document box (tell me that task(s) the application is to accomplish, how it will accomplish the tasks, the author of...

  • Please help with Java test questions, I will post the rest of the question in separate...

    Please help with Java test questions, I will post the rest of the question in separate post. Question 1 Consider the following program: public class CountDownApp3 {     public static void main(String[] args)     {         Thread t1 = new CountDown();         Thread t2 = new CountDown();         t1.start();         t2.start();     } } Assuming that the CountDown class extends the Thread class, how many threads are used to run this program? a. 3 b. 2 c. 4 d. 1...

  • Can you fix my error? I created a program that changes labels every second in Java....

    Can you fix my error? I created a program that changes labels every second in Java. But, it does not change. And, it will starts with second label. This is also an error. import java.awt.BorderLayout; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.Timer; public class Map2 extends JFrame{ JPanel panel; JLabel pic; Timer tm; int x = 0; String ly = "<html> " + "<br> <font size='10' color='red'> <b> 111111111 <b/> </font>...

  • please help with the TODO's in bold below! * Java application: CS140_Arrays.java * * Need to...

    please help with the TODO's in bold below! * Java application: CS140_Arrays.java * * Need to be done! * * TODO#1: Change the name and date accordingly * Created by , 11/25/2019 */ public class CS140_Arrays_Done { //TODO#2: Define two private static constants: rows (set to 5) & cols (set to 3) //array for the values private static double[][] values = { { 9, 10, 8 }, { 3.5, 10, 8.5 }, { 10, 8.5, 9 }, { 8.5, 10,...

  • I am suppose to have my array before the main class but I am getting the...

    I am suppose to have my array before the main class but I am getting the error 7 errors found: File: C:\Users\diego\OneDrive\Desktop\school\Spring 2020 classes\How to program java (Late Objects)\PO1\Test_ResidencePolicy.java [line: 60] Error: non-static variable objectArray cannot be referenced from a static context File: C:\Users\diego\OneDrive\Desktop\school\Spring 2020 classes\How to program java (Late Objects)\PO1\Test_ResidencePolicy.java [line: 61] Error: non-static variable objectArray cannot be referenced from a static context File: C:\Users\diego\OneDrive\Desktop\school\Spring 2020 classes\How to program java (Late Objects)\PO1\Test_ResidencePolicy.java [line: 67] Error: non-static variable objectArray cannot...

  • I need help with my IM (instant messaging) java program, I created the Server, Client, and...

    I need help with my IM (instant messaging) java program, I created the Server, Client, and Message class. I somehow can't get both the server and client to message to each other. I am at a roadblock. Here is the question below. Create an IM (instant messaging) java program so that client and server communicate via serialized objects (e.g. of type Message). Each Message object encapsulates the name of the sender and the response typed by the sender. You may...

  • With a Scanner object created as follows, what method do you use to read an int...

    With a Scanner object created as follows, what method do you use to read an int value? Scanner input = new Scanner(System.in); A. input.int(); B. input.nextInt(); C. input.integer(); D. input.nextInteger(); What is the output of the following code? x = 0; if (x > 0) System.out.println("x is greater than 0"); else if (x < 0) System.out.println("x is less than 0"); else System.out.println("x equals 0"); A. x is greater than 0 B. x is less than 0 C. x equals 0...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT