0% found this document useful (0 votes)
2 views44 pages

Lecture 07 10 Garbag Array

The document provides an overview of memory allocation in Java, focusing on stack and heap memory, their characteristics, and the garbage collection process. It explains how objects are created, the concept of garbage, and various garbage collection schemes such as reference counting and mark-and-sweep. Additionally, it introduces arrays in Java, including their declaration, initialization, and processing techniques.

Uploaded by

neeltrial1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views44 pages

Lecture 07 10 Garbag Array

The document provides an overview of memory allocation in Java, focusing on stack and heap memory, their characteristics, and the garbage collection process. It explains how objects are created, the concept of garbage, and various garbage collection schemes such as reference counting and mark-and-sweep. Additionally, it introduces arrays in Java, including their declaration, initialization, and processing techniques.

Uploaded by

neeltrial1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 44

Introduction to garbage

collection and array in Java

R. S. Yadav
Memory Allocation
The JVM divides memory into stack and heap memory.
Stack Memory in Java is used for static memory allocation and the execution of a thread.
It contains primitive values that are specific to a method and references to objects
referred from the method that are in a heap.

Key Features of Stack Memory

Some other features of stack memory include:


● It grows and shrinks as new methods are called and returned, respectively.
● Variables inside the stack exist only as long as the method that created them is
running.
● It's automatically allocated and deallocated when the method finishes execution.
● If this memory is full, Java throws java.lang.StackOverFlowError.
● Access to this memory is fast when compared to heap memory.
● This memory is threadsafe, as each thread operates in its own stack.
Memory Allocation
Heap space is used for the dynamic memory allocation of new created objects and JRE
classes at runtime. New objects are always created in heap space, and the references to these
objects are stored in stack memory.

These objects have global access and we can access them from anywhere in the application.

We can break this memory model down into smaller parts, called generations, which are:
1. Young Generation – this is where all new objects are allocated and aged. A minor
Garbage collection occurs when this fills up.
2. Old or Tenured Generation – this is where long surviving objects are stored. When
objects are stored in the Young Generation, a threshold for the object's age is set, and
when that threshold is reached, the object is moved to the old generation.
3. Permanent Generation – this consists of JVM metadata for the runtime classes and
application methods.
Memory Allocation
Key Features of Java Heap Memory

● It's accessed via complex memory management techniques that include the Young
Generation, Old or Tenured Generation, and Permanent Generation.
● If heap space is full, Java throws java.lang.OutOfMemoryError.
● Access to this memory is comparatively slower than stack memory
● This memory, in contrast to stack, isn't automatically deallocated. It needs Garbage
Collector to free up unused objects so as to keep the efficiency of the memory usage.
● Unlike stack, a heap isn't threadsafe and needs to be guarded by properly synchronizing
the code.
Memory Allocation
class Person {
int id;
String name;

public Person(int a, String b) {


id = a;
name = b; }}

public static void main(String[] args) {


int id = 23;
String name = "John";
Person person = new Person( 23, John); }}
Let's analyze this step-by-step:
1. When we enter the main() method, a space in stack memory is created .
● Stack memory directly stores the primitive value of integer id, string name.
● The reference of object name person of class Person and point actual object
created in heap.
2. Heap memory will store all instance variables for the newly created object .
Garbage Collection
• What is garbage and how can we deal with it?

• Garbage collection schemes

• Reference Counting
• Mark and Sweep
How Objects are Created in Java

• An object is created in Java by invoking the new()


operator.

• Calling the new() operator, the JVM will do the


following:

• allocate memory;
• assign fields their default values;
• run the constructor;
• a reference is returned.
How Java Reclaims Objects Memory

• Java does not provide the programmer any means to


destroy objects explicitly

• The advantages are

– No dangling reference problem in Java (i.e. in C & C++)

– Easier programming

– No memory leak problem (i.e. in C & C++)


?What is Garbage

Ali Object
Garbage: unreferenced objects

Student ali= new Student(); ail


Student khalid= new Student();
ali=khalid;
khalid
Now ali Object becomes a garbage,
It is unreferenced Object
Khalid Object
?What is Garbage Collection
• What is Garbage Collection?
– Finding garbage and reclaiming memory allocated to it.

• Why Garbage Collection?


– the heap space occupied by an un-referenced object can be
recycled and made available for subsequent new objects

• When is the Garbage Collection process invoked?


– When the total memory allocated to a Java program
exceeds some threshold.

• Is a running program affected by garbage collection?


– Yes, the program suspends during garbage collection.
Advantages of Garbage Collection

• Garbage collection eliminates the need for the programmer to


deallocate memory blocks explicitly

• Garbage collection helps ensure program integrity.

• Garbage collection can also dramatically simplify programs.


Disadvantages of Garbage Collection

• Garbage collection adds an overhead that can affect program


performance.

• Garbage collection requires extra memory.

• Programmers have less control over the scheduling of CPU


time.
Helping the Garbage Collector
• Reuse objects instead of generating new ones.
– This program generates one million objects and prints them out,
generating a lot of garbage
for (int i=0;i<1000000; ++i) {
SomeClass obj= new SomeClass(i);
System.out.println(obj);
}
– Using only one object and implementing the setInt() method, we
dramatically reduce the garbage generated.
SomeClass obj= new SomeClass();
for (int i=0;i< 1000000; ++i) {
obj.setInt(i);
System.out.println(onj);
}
• Eliminate all references to objects that are no longer needed
– This can be done by assigning null to every variable that refers to an
object that is no longer needed
Common Garbage Collection Schemes
• Main methods of garbage collection:

– Reference counting

– Mark-and-sweep
Reference Counting Garbage Collection

• Main Idea: Add a reference count field for every


object.

• This Field is updated when the number of references


to an object changes.
p
57
Example
refCount = 2
Object p= new Integer(57);
q
Object q = p;
Reference Counting (cont'd)
• The update of reference field when we have a reference
assignment ( i.e p=q) can be implemented as follows

if (p!=q)
Example:
{ Object p = new Integer(57);
if (p!=null) Object q= new Integer(99);
--p.refCount; p=q

p=q;
p
if (p!=null) 57
++p.refCount;
refCount = 0
}
q

99

refCount = 2
Reference Counting (cont'd)
• Reference counting will fail whenever the data
structure contains a cycle of references and the cycle
is not reachable from a global or local reference

head ListElements ListElements ListElements

next next next

refCount = 1 refCount = 1 refCount = 1


Reference Counting (cont'd)
• Advantages
– Conceptually simple: Garbage is easily identified
– It is easy to implement.
– Immediate reclamation of storage
– Objects are not moved in memory during garbage
collection.

• Disadvantages
– Reference counting does not detect garbage with cyclic
references.
– The overhead of incrementing and decrementing the
reference count each time.
– Extra space: A count field is needed in each object.
– It may increase heap fragmentation.
Mark-and-Sweep Garbage Collection
• The mark-and-sweep algorithm is divided into
two phases:
– Mark phase: the garbage collector traverses the
graph of references from the root nodes and marks
each heap object it encounters. Each object has an
extra bit: the mark bit – initially the mark bit is 0. It is
set to 1 for the reachable objects in the mark phase.
– Sweep phase: the Garbage collection scans the heap
looking for objects with mark bit 0 – these objects
have not been visited in the mark phase – they are
garbage. Any such object is added to the free list of
objects that can be reallocated. The objects with a
mark bit 1 have their mark bit reset to 0.
Mark and Sweep (cont'd)

• Advantages
– It is able to reclaim garbage that contains cyclic
references.
– There is no overhead in storing and manipulating
reference count fields.
– Objects are not moved during Garbage collection – no
need to update the references to objects.
• Disadvantages
– It may increase heap fragmentation.
– It does work proportional to the size of the entire
heap.
– The program must be halted while garbage collection
is being performed.
Four States of Memory Chunks
1. Free = not holding an object; available
for allocation.
2. Unreached = Holds an object, but has
not yet been reached from the root set.
3. Unscanned = Reached from the root
set, but its references not yet followed.
4. Scanned = Reached and references
followed.

21
Mark and Sweep Algorithm
Garbage Detection
Depth-first search to mark live data
cells (cells in heap reachable from
.variables on run-time stack)
Garbage Reclamation
Sweep through entire memory,
putting unmarked nodes on freelist.
Sweep also unmarks the marked
.nodes
22 L9GC ceg860 (Prasad)
Mark-and-Sweep
Basic idea
go through all memory and mark every
chunk that is referenced
make a second pass through memory and
remove all chunks not marked
OS 0 1 2 3
p2 = 650 p2 = 360

0 10 35 45 60
0 0 0 0

Mark chunks 0, 1, and 3 as marked•


Place chunk 2 on the free list (turn it into a•
hole)
Mark and Sweep Example

root A 0 B 0 C 0 D 0 E 0 F 0

free
:After mark

root A 1 B 0 C 1 D 0 E 0 F 1

free
:After sweep

root A 0 B 0 C 0 D 0 E 0 F 0

free

24 L9GC ceg860 (Prasad)


25

Introducing Arrays
Array is a data structure that represents a collection of the
same types of data.
double[] myList = new double[10];

myList reference
myList[0] 5.6
myList[1] 4.5
Array reference myList[2] 3.3
variable
myList[3] 13.2

myList[4] 4
Array element at
myList[5] 34.33 Element value
index 5
myList[6] 34

myList[7] 45.45

myList[8] 99.993

myList[9] 11123

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
26

Declaring Array Variables


• datatype[] arrayRefVar;
Example:
double[] myList;

• datatype arrayRefVar[]; // This style is


allowed, but not preferred
Example:
double myList[];

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
27

Creating Arrays
arrayRefVar = new datatype[arraySize];

Example:
myList = new double[10];

myList[0] references the first element in the array.


myList[9] references the last element in the array.

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
28

Declaring and Creating


in One Step

• datatype[] arrayRefVar = new


datatype[arraySize];
double[] myList = new double[10];

• datatype arrayRefVar[] = new


datatype[arraySize];
double myList[] = new double[10];

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
29

The Length of an Array


Once an array is created, its size is fixed. It cannot
be changed. You can find its size using

arrayRefVar.length

For example,

myList.length returns 10

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
30

Default Values
When an array is created, its elements are
assigned the default value of

0 for the numeric primitive data types,


'\u0000' for char types, and
false for boolean types.

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
31

Array Initializers

• Declaring, creating, initializing in one step:


double[] myList = {1.9, 2.9, 3.4, 3.5};

This shorthand syntax must be in one


statement.

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
32

Declaring, creating, initializing Using the


Shorthand Notation
double[] myList = {1.9, 2.9, 3.4, 3.5};
This shorthand notation is equivalent to the following
statements:
double[] myList = new double[4];
myList[0] = 1.9;
myList[1] = 2.9;
myList[2] = 3.4;
myList[3] = 3.5;

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
33

Processing Arrays
1. (Initializing arrays)
2. (Printing arrays)
3. (Summing all elements)
4. (Finding the largest element)
5. (Finding the smallest index of the
largest element)

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
34

Enhanced for Loop


JDK 1.5 introduced a new for loop that enables you to traverse the
complete array sequentially without using an index variable. For example,
the following code displays all elements in the array myList:

for (double value: myList)


System.out.println(value);

In general, the syntax is

for (elementType value: arrayRefVar) {


// Process the value
}

You still have to use an index variable if you wish to traverse the array in a
different order or change the elements in the array.

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
35

Example: Testing Arrays


• Objective: The program receives 6 numbers
from the user, finds the largest number and
counts the occurrence of the largest number
entered.
Suppose you entered 3, 5, 2, 5, 5, and 5, the
largest number is 5 and its occurrence count is
4.

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
36

Two-dimensional Arrays
// Declare array ref var
dataType[][] refVar;

// Create array and assign its reference to variable


refVar = new dataType[10][10];

// Combine declaration and creation in one statement


dataType[][] refVar = new dataType[10][10];

// Alternative syntax
dataType refVar[][] = new dataType[10][10];

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
37

Declaring Variables of Two-


dimensional Arrays and Creating Two-
dimensional Arrays

int[][] matrix = new int[10][10];


or
int matrix[][] = new int[10][10];
matrix[0][0] = 3;

for (int i = 0; i < matrix.length; i++)


for (int j = 0; j < matrix[i].length; j++)
matrix[i][j] = (int)(Math.random() * 1000);

double[][] x;

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
38

Two-dimensional Array Illustration


0 1 2 3 4 0 1 2 3 4 0 1 2
0 0 0 1 2 3

1 1 1 4 5 6

2 2 7 2 7 8 9

3 3 3 10 11 12

4 4 int[][] array = {
{1, 2, 3},
matrix = new int[5][5]; matrix[2][1] = 7; {4, 5, 6},
{7, 8, 9},
{10, 11, 12}
};

matrix.length? 5 array.length? 4
matrix[0].length? 5 array[0].length? 3

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
39

Declaring, Creating, and Initializing Using Shorthand Notations

You can also use an array initializer to declare, create


and initialize a two-dimensional array. For example,

{ = int[][] array ;int[][] array = new int[4][3]


,}3 ,2 ,1{ ;array[0][0] = 1; array[0][1] = 2; array[0][2] = 3
,}6 ,5 ,4{ Same as ;array[1][0] = 4; array[1][1] = 5; array[1][2] = 6
,}9 ,8 ,7{ ;array[2][0] = 7; array[2][1] = 8; array[2][2] = 9
}12 ,11 ,10{ ;array[3][0] = 10; array[3][1] = 11; array[3][2] = 12
;}

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
40

Lengths of Two-dimensional Arrays

int[][] x = new int[3][4];

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
41

Lengths of Two-dimensional Arrays, cont.

int[][] array = { array.length


{1, 2, 3}, array[0].length
{4, 5, 6}, array[1].length
{7, 8, 9}, array[2].length
{10, 11, 12} array[3].length
};

array[4].length ArrayIndexOutOfBoundsException

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
42

Ragged Arrays
Each row in a two-dimensional array is itself an array.
So, the rows can have different lengths. Such an
array is known as a ragged array. For example,
int[][] matrix = {
{1, 2, 3, 4, 5}, matrix.length is 5
{2, 3, 4, 5}, matrix[0].length is 5
{3, 4, 5}, matrix[1].length is 4
matrix[2].length is 3
{4, 5}, matrix[3].length is 2
{5} matrix[4].length is 1
};
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
43

Problems sheet on array


Note: You are required to write the program in java using object oriented concept where a
small functionality is required to be used as member function of a class. Further, data are
represented form of array. Also write the abstract of classes.
1.Convert integer decimal number to binary number
2.Convert floating point decimal number to binary number
3.Convert binary number to floating point decimal number
4.Count the number of 1’s in binary number using shift ( left or right) operators.
5.You are required to generate a four bit cyclic binary counter that starts counting in upward
direction from given value and on reaching to the highest value of counting starts counting in
reverse direction up to the given value for upward counting. It repeat the cycle. Your program
get binary input from user and display each output as four binary digits starting from most
significant digit to the least significant digit. Further, you are required to add a delay of
10000 iteration using for loop between two consecutive output displayed. The display must
be sufficient for distinguishing two consecutive displays.
6.Sort an integer array in ascending order using bubble sort.
7.Merge two ascending order sorted integer array into ascending order sorted array.

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
44

Problems sheet on array (cont.)

Note: You are required to write the program in java using object oriented concept where a
small functionality is required to be used as member function of a class. Further, data are
represented form of array.
8.Merge two ascending order sorted integer array into descending order sorted array.
9.Merge two sorted integer array where first one is in ascending order while second one in
descending order into ascending order sorted array.
10.Sort an integer array in ascending order using merge sort.
11.You are required to compute the following activities on two dimensional integer array.
i. Transpose the array.
ii. Sum the diagonal elements.
iii. Print the upper triangular of the array.
iv. add the two arrays.
v. multiply two arrays.

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6

You might also like