Question

Demonstrate the following in java: Proper handling of memory and objects to avoid memory leaks

Demonstrate the following in java:

Proper handling of memory and objects to avoid memory leaks

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

1.First of all what is memory leak

A Memory Leak is a situation when there are objects present in the heap that are no longer used, but the garbage collector is unable to remove them from memory and, thus they are unnecessarily maintained. A memory leak is bad because it blocks memory resources and degrades system performance over time.

A memory leak is bad because it blocks memory resources and degrades system performance over time. And if not dealt with, the application will eventually exhaust its resources, finally terminating with a fatal java.lang.OutOfMemoryError.

2. Why does it occurs

Java does automatic Garbage collection. However there can be situations where garbage collector does not collect objects because there are references to them. There might be situations where an application creates lots of objects and does not use them. Just because every objects has valid references, garbage collector in Java can’t destroys the objects. Such types of useless objects are called as Memory leaks. If allocated memory goes beyond limit, program will be terminated by rising OutOfMemoryError.

3 .Now the question arises how to handle object to avoid memory leak

* To get rid of memory leak you can  reference objects

EXPLANATION OF ABOVE POINT:

Using the java.lang.ref package, you can work with the garbage collector in your program. This allows you to avoid directly referencing objects, but use special reference objects that are easily cleared by the garbage collector. The special subclasses allow you to refer to objects indirectly. For instance, Reference has three subclasses: PhantomReference, SoftReference, and WeakReference.

A referent, or an object that is referenced by these subclasses, can be accessed using that reference object’s get method.How does garbage collector act with each type of referent?

  • SoftReference object: Garbage collector is required to clear all SoftReference objects when memory runs low.
  • WeakReference object: When garbage collector senses a weakly referenced object, all references to it are cleared and ultimately taken out of memory.
  • PhantomReference object: Garbage collector would not be able to automatically clean up PhantomReference objects, you would need to clean it up manually by clearing all references to it.

ADVANTAGES

  • The advantage of using this method is that you can clear a reference easily by setting it to null and that the reference is pretty much immutable, or it cannot be changed.
  • With the use of reference objects, you can work with the garbage collector to automate the task of removing listeners that are weakly reachable. WeakReference objects, especially with a cleanup thread, can help you avoid memory errors.

4.Other ways to prevent memory leak

  • Release the session when it is no longer needed. Use the HttpSession.invalidate() to do this.
  • Keep the time-out time low for each session.
  • Store only the necessary data in your HttpSession.
  • Avoid using string concatenation. Use StringBuffer’s append() method because the string is an unchangeable object while string concatenation creates a lot of unnecessary objects. A large number of temporary objects will slow down performance.
  • As much as possible, you should not create HttpSession in your jsp page. You can do this by using the page directive <%@page session=”false”%>.
  • If you are writing a query that is frequently executed, use PreparedStatement object rather than using Statement object. Why? PreparedStatement is precompiled while Statement is compiled every time your SQL statement is transmitted to the database.
  • When using JDBC code, avoid using “*” when you write your query. Try to use the corresponding column name instead.
  • If you are going to use stmt = con.prepareStatement(sql query) within a loop, then be sure to close it inside that particular loop.
  • Be sure to close the Statement and ResultSet when you need to reuse these.
  • Close the ResultSet, Connection, PreparedStatement, and Statement in the finally block.

Thanks hope it will help you!

if does then please rate

Add a comment
Know the answer?
Add Answer to:
Demonstrate the following in java: Proper handling of memory and objects to avoid memory leaks
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
  • The kernel is responsible for which of the following: A. memory leaks B.Restoring the computers operating...

    The kernel is responsible for which of the following: A. memory leaks B.Restoring the computers operating system C.database backup D.Interrupt Handling C.all of the above

  • 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...

  • Q.25. Given the following program, you are asked to discuss memory leaks caused in its execution....

    Q.25. Given the following program, you are asked to discuss memory leaks caused in its execution. Determine which memory locations get uncontrolled. (2 points) 4 6 7 8 9 10 11 12 B 13 14 15 16 17 18 1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 5 void main() { char *aString = "Memory leaks?"; char **strList; int i, n = 5; strlist = (char**)malloc(n*sizeof(char*)); for (i=0; i<n; i++) { printf("\nstring %d ", i+1); strList[i] = (char*)malloc(50*sizeof (char));...

  • For the efficient memory management and to avoid errors modern systems uses secondary memory as a...

    For the efficient memory management and to avoid errors modern systems uses secondary memory as a part of the main memory known as a virtual memory. When a computer system is running serval programs at the same time, the main memory often becomes exhausted. In such circumstances instead of closing some programs the operating system use the secondary memory as part of the main memory to store some data. In short virtual memory is an elegant interaction of hardware exceptions,...

  • Starting Out With Java early Objects by Tony Gladdis The class to be modified is found...

    Starting Out With Java early Objects by Tony Gladdis The class to be modified is found in Code Listing 6-29 section on pgs 417-418 in the book 'Starting Out With Java early Objects by Tony Gladdis the 5th Edition' 7. RetailItem Class Modification Modify this chapter’s RetailItem class (which uses an inner class named CostData) to include accessor and mutator methods for getting and setting an item’s wholesale and retail cost. Demonstrate the methods in a program. Thanks

  • java help plz. 6. Consider these questions about memory-answers are in HFJ Chapter 3 a. (5...

    java help plz. 6. Consider these questions about memory-answers are in HFJ Chapter 3 a. (5 pts) Assuming the same JVM, can the amount of memory taken up by an object reference differ for different kinds of objects (say String vs ArrayList<String>?) b. (5 pts) Assuming the same JVM, can the amount of memory taken up by the object itself differ for different kinds of objects .(5 pts) Can the amount of memory taking up for an object reference for...

  • Which of the following outcomes is a result of proper error-handling procedures in secure code? A.Execution...

    Which of the following outcomes is a result of proper error-handling procedures in secure code? A.Execution continues with no notice or logging of the error condition. B.Minor fault conditions result in the system stopping to preserve state. C.The program runs through to completion with no detectable impact on output. D.All fault conditions are logged and do not result in a program crash

  • 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());         }    ...

  • Purpose: The JAVA application will allow the student to; I. demonstrate the declaration of an array;...

    Purpose: The JAVA application will allow the student to; I. demonstrate the declaration of an array; II. demonstrate the initialization of the array; III demonstrate the printing of the elements of the array. Create a new file called "Array5A” . 1. Prepare a document box (tell me that task(s) the application is to accomplish, how it will accomplish the tasks, the author of the application, the date of completion, and any additional notes.) 2. Write a Java statement to create...

  • I need a simple java program that contains all the following subjects : 1- OOP Objects...

    I need a simple java program that contains all the following subjects : 1- OOP Objects -Classes 2- Encapsulation 3- Polymorphism 4-Inheritance 4- Abstract Classes

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