SlideShare a Scribd company logo
MEMORY MANAGEMENT
in JAVA
STACK SPACE, HEAP
SPACE AND STRING
POOLS
JAVATHLON.COM BY TALHA OCAKÇI
MOTIVATION
javathlon.com by Talha Ocakçı
What happens when you run this code:
A) Operating system fails. Because all memory is exhausted by our program.
B) All running programs lose data since all memory is exhausted by our program.
C) Operating system does not allow program execution by detecting the memory consumption.
D) Program halts and throw an error.
JVM MEMORY
javathlon.com by Talha Ocakçı
OPERATING
SYSTEM
MEMORY
JVM MEMORY
(CONSTANT)
When main method is executed, JVM asks for some memory from
the OS and size of this space can not be changed during the
program execution.
JVM MEMORY
 Every object is stored in JVM memory and can be
accessed by its address value.
 A Java application can not interfere with a
memory block outside the JVM.
JAVATHLON.COM BY TALHA OCAKÇI
Memory Management
javathlon.com by Talha Ocakçı
HEAP AREA STACK AREA NON-HEAP AREA
Class instances and arrays Stacks for executing methods per
thread
Permanent Generation
1. Per-class data
2. Interned Strings
HEAP AREA
▪ Objects (excluding interned strings) created in any
thread are stored in this area. So this is a common
place for all threads.
▪ Interned strings stored in non-heap area
separately.
javathlon.com by Talha Ocakçı
HEAP AREA
▪ If you create an object with new() keyword, it will
be stored in heap area.
▪If no reference left for a given object, it will be a
candidate for garbage collection.
javathlon.com by Talha Ocakçı
STACK AREA
JAVATHLON.COM BY TALHA OCAKÇI
MOTIVATION
javathlon.com by Talha Ocakçı
We will try to
swap the
customers and
see if they were
really swapped.
WHAT IS STACK?
Element 2
Element 1
Element 1
Element 2
Element 1
Element 1
JAVATHLON.COM BY TALHA OCAKÇI
HOW IS METHOD ORDER
PRESERVED?
When a method
is called,
method-specific
data is collected,
tied together and
put into stack
space. It is
removed when
the execution is
done.
JAVATHLON.COM BY TALHA OCAKÇI
secondMethod
firstMethod
Element 1
firstMethod
firstMethod
secondMethod
secondMethod
firstMethod
thirdMethod
secondMethod
firstMethod
firstMethod
thirdMethod
Stack frame
JAVATHLON.COM BY TALHA OCAKÇI
STACK SPACE
JVM uses this space for controlling the execution of
methods.
 Stores local values of ongoing methods.
 Stores signatures of ongoing methods.
JAVATHLON.COM BY TALHA OCAKÇI
STACK AREA
javathlon.com by Talha Ocakçı
Stack for
Thread 1
Stack
for
method
A
Stack for
Thread 2
Stack frame per method
Stack frame per method
Stack frame per method
Stack frame per method
Stack area
For each thread, a stack is stored.
Each stack stores a stack frame per
method call. Stack frame stores return
type, arguments and address values of
local objects and values of local
primitive values.
STACK FRAME
Stored
information
Value
Arguments String
Local object
(customer)
0x65899
Local primitive
(age)
30
Return value True
…
JAVATHLON.COM BY TALHA OCAKÇI
STACK FRAMES
Located in a stack allocated to a thread in stack area. Stores
1. Address values of local objects
2. Values of local primitives
3. Return value of the method
4. Current class’s definition’s address value
5. Operands stack
javathlon.com by Talha Ocakçı
MOTIVATION
javathlon.com by Talha Ocakçı
What happens when you run
this code?
A) Prints 5 infinitely
B) Exhausts all the memory of
JVM
C) Throws an exception
MOTIVATION
javathlon.com by Talha Ocakçı
Stack space is limited. Here,
without popping a stack frame from
the stack, a new one is pushed. So
allocated memory for method
information grows rapidly.
JVM throws a
StackOverflowException and halts
the execution.
PASSING OBJECTS in JAVA
javathlon.com by Talha Ocakçı
In Java, objects are passed between
methods by their values.
1. Objects are passed by values of their
address on heap space
2. Primitives are passed by values
3. Strings are also passed by values of
their value. This value is checked against
the interned strings in non-heap area.
EXAMPLE
javathlon.com by Talha Ocakçı
We will try to
swap the
customers and
See if they were
really swapped.
javathlon.com by Talha Ocakçı
...
HEAP SPACE
1
Talha
Turkey
2
John
US
customer1 1000
customer2 2000
1000
2000
Stack frame for main method
public void swapCustomers(Customer cust1, Customer cust2) {
Customer temp = cust2;
cust2 = cust1;
cust1 = temp;
}
javathlon.com by Talha Ocakçı
...
HEAP SPACE
1
Talha
Turkey
2
John
US
customer1 1000
customer2 2000
1000
2000
Stack frame for main method
public void swapCustomers(Customer cust1, Customer cust2) {
Customer temp = cust2;
cust2 = cust1;
cust1 = temp;
}
cust1 1000
cust2 2000
Stack frame for swapCustomers method
javathlon.com by Talha Ocakçı
...
HEAP SPACE
1
Talha
Turkey
2
John
US
customer1 1000
customer2 2000
1000
2000
Stack frame for main method
public void swapCustomers(Customer cust1, Customer cust2) {
Customer temp = cust2;
cust2 = cust1;
cust1 = temp;
}
temp 2000
cust1 1000
cust2 2000
Stack frame for swapCustomers method
javathlon.com by Talha Ocakçı
...
HEAP SPACE
1
Talha
Turkey
2
John
US
customer1 1000
customer2 2000
1000
2000
Stack frame for main method
public void swapCustomers(Customer cust1, Customer cust2) {
Customer temp = cust2;
cust2 = cust1;
cust1 = temp;
}
temp 2000
cust1 1000
cust2 1000
Stack frame for swapCustomers method
javathlon.com by Talha Ocakçı
...
HEAP
SPACE
1
Talha
Turkey
2
John
US
customer1 1000
customer2 2000
1000
2000
Stack frame for main method
public void swapCustomers(Customer cust1, Customer cust2) {
Customer temp = cust2;
cust2 = cust1;
cust1 = temp;
}
temp 2000
cust1 2000
cust2 1000
Stack frame for swapCustomers method
javathlon.com by Talha Ocakçı
...
HEAP
SPACE
1
Talha
Turkey
2
John
US
customer1 1000
customer2 2000
1000
2000
Stack frame for main method
public void swapCustomers(Customer cust1, Customer cust2) {
Customer temp = cust2;
cust2 = cust1;
cust1 = temp;
}
temp 2000
cust1 2000
cust2 1000
Stack frame for swapCustomers method
javathlon.com by Talha Ocakçı
...
HEAP SPACE
1
Talha
Turkey
2
John
US
customer1 1000
customer2 2000
1000
2000
Stack frame for main method
public void swapCustomers(Customer cust1, Customer cust2) {
Customer temp = cust2;
cust2 = cust1;
cust1 = temp;
}
So nothing has been changed on
Customer1 and customer2 references.
SECOND EXAMPLE
javathlon.com by Talha Ocakçı
We will pass the
object to a method,
change some
attributes of it and
check whether the
original object has
been changed.
javathlon.com by Talha Ocakçı
...
HEAP
SPACE
1
Talha
Turkey
customer1 1000
1000
Stack frame for main method
public void changeCountry(Customer cust) {
cust.address = "new zealand";
}
javathlon.com by Talha Ocakçı
...
HEAP
SPACE
1
Talha
Turkey
customer1 1000
1000
Stack frame for main method
public void changeCountry(Customer cust) {
cust.address = "new zealand";
}
cust 1000
javathlon.com by Talha Ocakçı
...
HEAP
SPACE
1
Talha
new zealand
customer1 1000
1000
Stack frame for main method
public void changeCountry(Customer cust) {
cust.address = "new zealand";
}
cust 1000
Stack frame for changeCountry method
javathlon.com by Talha Ocakçı
...
HEAP
SPACE
1
Talha
new zealand
customer1 1000
1000
Stack frame for main method
public void changeCountry(Customer cust) {
cust.address = "new zealand";
}
So, the original object is really
modified on heap space
EXAMPLE 3
javathlon.com by Talha Ocakçı
We will send a
primitive to a
method,
multiply the
argument value and
will check
Whether te original
value has been
changed.
javathlon.com by Talha Ocakçı
...
HEAP
SPACE
x 10
Stack frame for main method
public void doubleTheValue(int value)
{
value = value *2;
}
Since there is no object defined,
no object exists for this program
value 10
Stack frame for doubleTheValue method
javathlon.com by Talha Ocakçı
...
HEAP
SPACE
x 10
Stack frame for main method
public void doubleTheValue(int value)
{
value = value *2;
}
Since there is no object defined,
no object exists for this program
value 20
Stack frame for doubleTheValue method
javathlon.com by Talha Ocakçı
...
HEAP
SPACE
x 10
Stack frame for main method
public void doubleTheValue(int value)
{
value = value *2;
}
Since there is no object defined,
no object exists for this program
Example 4
javathlon.com by Talha Ocakçı
Now we will try the same thing with
a String. We will demonstrate the special
case of the String class and string interning
idea.
Example 4
javathlon.com by Talha Ocakçı
This code will output «current».
Because updateValue method could not
change the value of String string variable
The reason is string interning also
known as «string pooling».
Lets start with an example
javathlon.com by Talha Ocakçı
What is the output of this code snippet?
Lets start with an example
javathlon.com by Talha Ocakçı
If you answered this as «true», you
probably know what is going on.
Second example
javathlon.com by Talha Ocakçı
What is the output of this code snippet?
Second example
javathlon.com by Talha Ocakçı
Answer is «false»
Third example
javathlon.com by Talha Ocakçı
Now, let’s try it with string interning.
Output is true.
Now lets inspect what is going on.
String interning
One of the most used method in an ordinary program is string comparison. And in an average
program, there are so many strings which has an average length between 10-20.
So, to compare two strings, JVM must compare that much character everytime causing a real
performance problem. That’s why, JVM puts a used String to a String pool and uses the
internal HashMap for comparing the string variables.
javathlon.com by Talha Ocakçı
javathlon.com by Talha Ocakçı
...
STRING POOL
s1 6000
s2 6000
Stack frame for main method
String s1 = "talha_ocakci";
talha_ocakci
6000
String s2 = "talha_ocakci";
javathlon.com by Talha Ocakçı
...
STRING POOL
s1 6000
s2 6000
Stack frame for main method
String s1 = "talha_ocakci";
talha_ocakci
6000
String s2 = "talha_ocakci";
s1 == s2
6000 == 6000
true
javathlon.com by Talha Ocakçı
STRING POOL
s3 9500
s4 9600
Stack frame for main method
String s3 = new String("talha_ocakci");
String s4 = new String("talha_ocakci");
...
talha_ocakci
6000
HEAP
...
talha_ocakci
9500
talha_ocakci
9600
javathlon.com by Talha Ocakçı
STRING POOL
s3 9500
s4 9600
Stack frame for main method
String s3 = new String("talha_ocakci");
s3 = s3.intern();
String s4 = new String("talha_ocakci");
s4= s4.intern();
...
talha_ocakci
6000
HEAP
...
talha_ocakci
9500
talha_ocakci
9600
javathlon.com by Talha Ocakçı
STRING POOL
s3 6000
s4 6000
Stack frame for main method
String s3 = new String("talha_ocakci");
s3 = s3.intern();
String s4 = new String("talha_ocakci");
s4= s4.intern();
...
talha_ocakci
6000
HEAP
...
talha_ocakci
9500
talha_ocakci
9600
www.javathlon.com
By Talha OCAKÇI
JAVATHLON.COM BY TALHA OCAKÇI
Ad

More Related Content

What's hot (20)

Java Garbage Collection - How it works
Java Garbage Collection - How it worksJava Garbage Collection - How it works
Java Garbage Collection - How it works
Mindfire Solutions
 
File handling
File handlingFile handling
File handling
priya_trehan
 
Python with MySql.pptx
Python with MySql.pptxPython with MySql.pptx
Python with MySql.pptx
Ramakrishna Reddy Bijjam
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Tushar B Kute
 
Arrays in java
Arrays in javaArrays in java
Arrays in java
Arzath Areeff
 
Java annotations
Java annotationsJava annotations
Java annotations
FAROOK Samath
 
Data Types, Variables, and Operators
Data Types, Variables, and OperatorsData Types, Variables, and Operators
Data Types, Variables, and Operators
Marwa Ali Eissa
 
This keyword in java
This keyword in javaThis keyword in java
This keyword in java
Hitesh Kumar
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
kamal kotecha
 
TestNG - The Next Generation of Unit Testing
TestNG - The Next Generation of Unit TestingTestNG - The Next Generation of Unit Testing
TestNG - The Next Generation of Unit Testing
Bethmi Gunasekara
 
Java Method, Static Block
Java Method, Static BlockJava Method, Static Block
Java Method, Static Block
Infoviaan Technologies
 
Asp.NET Validation controls
Asp.NET Validation controlsAsp.NET Validation controls
Asp.NET Validation controls
Guddu gupta
 
Packages in java
Packages in javaPackages in java
Packages in java
Elizabeth alexander
 
Typescript in 30mins
Typescript in 30mins Typescript in 30mins
Typescript in 30mins
Udaya Kumar
 
7.data types in c#
7.data types in c#7.data types in c#
7.data types in c#
Zeeshan Ahmad
 
Java class,object,method introduction
Java class,object,method introductionJava class,object,method introduction
Java class,object,method introduction
Sohanur63
 
Java constructors
Java constructorsJava constructors
Java constructors
QUONTRASOLUTIONS
 
Operator overloading C++
Operator overloading C++Operator overloading C++
Operator overloading C++
Lahiru Dilshan
 
Java Basics
Java BasicsJava Basics
Java Basics
Brandon Black
 
java 8 new features
java 8 new features java 8 new features
java 8 new features
Rohit Verma
 
Java Garbage Collection - How it works
Java Garbage Collection - How it worksJava Garbage Collection - How it works
Java Garbage Collection - How it works
Mindfire Solutions
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Tushar B Kute
 
Data Types, Variables, and Operators
Data Types, Variables, and OperatorsData Types, Variables, and Operators
Data Types, Variables, and Operators
Marwa Ali Eissa
 
This keyword in java
This keyword in javaThis keyword in java
This keyword in java
Hitesh Kumar
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
kamal kotecha
 
TestNG - The Next Generation of Unit Testing
TestNG - The Next Generation of Unit TestingTestNG - The Next Generation of Unit Testing
TestNG - The Next Generation of Unit Testing
Bethmi Gunasekara
 
Asp.NET Validation controls
Asp.NET Validation controlsAsp.NET Validation controls
Asp.NET Validation controls
Guddu gupta
 
Typescript in 30mins
Typescript in 30mins Typescript in 30mins
Typescript in 30mins
Udaya Kumar
 
Java class,object,method introduction
Java class,object,method introductionJava class,object,method introduction
Java class,object,method introduction
Sohanur63
 
Operator overloading C++
Operator overloading C++Operator overloading C++
Operator overloading C++
Lahiru Dilshan
 
java 8 new features
java 8 new features java 8 new features
java 8 new features
Rohit Verma
 

Viewers also liked (20)

Performance Optimization and JavaScript Best Practices
Performance Optimization and JavaScript Best PracticesPerformance Optimization and JavaScript Best Practices
Performance Optimization and JavaScript Best Practices
Doris Chen
 
JAVA EE DEVELOPMENT (JSP and Servlets)
JAVA EE DEVELOPMENT (JSP and Servlets)JAVA EE DEVELOPMENT (JSP and Servlets)
JAVA EE DEVELOPMENT (JSP and Servlets)
Talha Ocakçı
 
Java
JavaJava
Java
Sneha Mudraje
 
Linked list (java platform se 8 )
Linked list (java platform se 8 )Linked list (java platform se 8 )
Linked list (java platform se 8 )
charan kumar
 
Java Stack Traces
Java Stack TracesJava Stack Traces
Java Stack Traces
dbanttari
 
Java Stack (Pilha)
Java Stack (Pilha)Java Stack (Pilha)
Java Stack (Pilha)
Samuel Santos
 
Introduction to java and oop
Introduction to java and oopIntroduction to java and oop
Introduction to java and oop
baabtra.com - No. 1 supplier of quality freshers
 
03 Java Language And OOP Part III
03 Java Language And OOP Part III03 Java Language And OOP Part III
03 Java Language And OOP Part III
Hari Christian
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
Nochiketa Chakraborty
 
01 introduction to oop and java
01 introduction to oop and java01 introduction to oop and java
01 introduction to oop and java
রাকিন রাকিন
 
Java Collections Framework Inroduction with Video Tutorial
Java Collections Framework Inroduction with Video TutorialJava Collections Framework Inroduction with Video Tutorial
Java Collections Framework Inroduction with Video Tutorial
Marcus Biel
 
Stack, queue and hashing
Stack, queue and hashingStack, queue and hashing
Stack, queue and hashing
Dumindu Pahalawatta
 
JAVA Object Oriented Programming (OOP)
JAVA Object Oriented Programming (OOP)JAVA Object Oriented Programming (OOP)
JAVA Object Oriented Programming (OOP)
Prof. Erwin Globio
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8
Talha Ocakçı
 
Oop java
Oop javaOop java
Oop java
Minal Maniar
 
My lecture stack_queue_operation
My lecture stack_queue_operationMy lecture stack_queue_operation
My lecture stack_queue_operation
Senthil Kumar
 
Java OOP Programming language (Part 3) - Class and Object
Java OOP Programming language (Part 3) - Class and ObjectJava OOP Programming language (Part 3) - Class and Object
Java OOP Programming language (Part 3) - Class and Object
OUM SAOKOSAL
 
OOP java
OOP javaOOP java
OOP java
xball977
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
backdoor
 
Encapsulation
EncapsulationEncapsulation
Encapsulation
Githushan Gengaparam
 
Performance Optimization and JavaScript Best Practices
Performance Optimization and JavaScript Best PracticesPerformance Optimization and JavaScript Best Practices
Performance Optimization and JavaScript Best Practices
Doris Chen
 
JAVA EE DEVELOPMENT (JSP and Servlets)
JAVA EE DEVELOPMENT (JSP and Servlets)JAVA EE DEVELOPMENT (JSP and Servlets)
JAVA EE DEVELOPMENT (JSP and Servlets)
Talha Ocakçı
 
Linked list (java platform se 8 )
Linked list (java platform se 8 )Linked list (java platform se 8 )
Linked list (java platform se 8 )
charan kumar
 
Java Stack Traces
Java Stack TracesJava Stack Traces
Java Stack Traces
dbanttari
 
03 Java Language And OOP Part III
03 Java Language And OOP Part III03 Java Language And OOP Part III
03 Java Language And OOP Part III
Hari Christian
 
Java Collections Framework Inroduction with Video Tutorial
Java Collections Framework Inroduction with Video TutorialJava Collections Framework Inroduction with Video Tutorial
Java Collections Framework Inroduction with Video Tutorial
Marcus Biel
 
JAVA Object Oriented Programming (OOP)
JAVA Object Oriented Programming (OOP)JAVA Object Oriented Programming (OOP)
JAVA Object Oriented Programming (OOP)
Prof. Erwin Globio
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8
Talha Ocakçı
 
My lecture stack_queue_operation
My lecture stack_queue_operationMy lecture stack_queue_operation
My lecture stack_queue_operation
Senthil Kumar
 
Java OOP Programming language (Part 3) - Class and Object
Java OOP Programming language (Part 3) - Class and ObjectJava OOP Programming language (Part 3) - Class and Object
Java OOP Programming language (Part 3) - Class and Object
OUM SAOKOSAL
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
backdoor
 
Ad

Similar to Heap and stack space in java (20)

Java 8
Java 8Java 8
Java 8
Sudipta K Paik
 
Introduction to apache_cassandra_for_develope
Introduction to apache_cassandra_for_developeIntroduction to apache_cassandra_for_develope
Introduction to apache_cassandra_for_develope
zznate
 
Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1
Todor Kolev
 
Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1
Todor Kolev
 
Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1
Todor Kolev
 
Java 7 & 8 - A&BP CC
Java 7 & 8 - A&BP CCJava 7 & 8 - A&BP CC
Java 7 & 8 - A&BP CC
JWORKS powered by Ordina
 
Java programing considering performance
Java programing considering performanceJava programing considering performance
Java programing considering performance
Roger Xia
 
OpenMP And C++
OpenMP And C++OpenMP And C++
OpenMP And C++
Dragos Sbîrlea
 
Best practices in Java
Best practices in JavaBest practices in Java
Best practices in Java
Mudit Gupta
 
How to debug slow lambda response times
How to debug slow lambda response timesHow to debug slow lambda response times
How to debug slow lambda response times
Yan Cui
 
Java String
Java String Java String
Java String
SATYAM SHRIVASTAV
 
Java interview-questions-and-answers
Java interview-questions-and-answersJava interview-questions-and-answers
Java interview-questions-and-answers
bestonlinetrainers
 
weblogic perfomence tuning
weblogic perfomence tuningweblogic perfomence tuning
weblogic perfomence tuning
prathap kumar
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and Concurrency
Rajesh Ananda Kumar
 
Владимир Иванов. Java 8 и JVM: что нового в HotSpot
Владимир Иванов. Java 8 и JVM: что нового в HotSpotВладимир Иванов. Java 8 и JVM: что нового в HotSpot
Владимир Иванов. Java 8 и JVM: что нового в HotSpot
Volha Banadyseva
 
Jvm Performance Tunning
Jvm Performance TunningJvm Performance Tunning
Jvm Performance Tunning
Terry Cho
 
Jvm Performance Tunning
Jvm Performance TunningJvm Performance Tunning
Jvm Performance Tunning
guest1f2740
 
Java interview questions 2
Java interview questions 2Java interview questions 2
Java interview questions 2
Sherihan Anver
 
Md04 flow control
Md04 flow controlMd04 flow control
Md04 flow control
Rakesh Madugula
 
Java 8 lambdas expressions
Java 8 lambdas expressionsJava 8 lambdas expressions
Java 8 lambdas expressions
Lars Lemos
 
Introduction to apache_cassandra_for_develope
Introduction to apache_cassandra_for_developeIntroduction to apache_cassandra_for_develope
Introduction to apache_cassandra_for_develope
zznate
 
Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1
Todor Kolev
 
Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1
Todor Kolev
 
Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1
Todor Kolev
 
Java programing considering performance
Java programing considering performanceJava programing considering performance
Java programing considering performance
Roger Xia
 
Best practices in Java
Best practices in JavaBest practices in Java
Best practices in Java
Mudit Gupta
 
How to debug slow lambda response times
How to debug slow lambda response timesHow to debug slow lambda response times
How to debug slow lambda response times
Yan Cui
 
Java interview-questions-and-answers
Java interview-questions-and-answersJava interview-questions-and-answers
Java interview-questions-and-answers
bestonlinetrainers
 
weblogic perfomence tuning
weblogic perfomence tuningweblogic perfomence tuning
weblogic perfomence tuning
prathap kumar
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and Concurrency
Rajesh Ananda Kumar
 
Владимир Иванов. Java 8 и JVM: что нового в HotSpot
Владимир Иванов. Java 8 и JVM: что нового в HotSpotВладимир Иванов. Java 8 и JVM: что нового в HotSpot
Владимир Иванов. Java 8 и JVM: что нового в HotSpot
Volha Banadyseva
 
Jvm Performance Tunning
Jvm Performance TunningJvm Performance Tunning
Jvm Performance Tunning
Terry Cho
 
Jvm Performance Tunning
Jvm Performance TunningJvm Performance Tunning
Jvm Performance Tunning
guest1f2740
 
Java interview questions 2
Java interview questions 2Java interview questions 2
Java interview questions 2
Sherihan Anver
 
Java 8 lambdas expressions
Java 8 lambdas expressionsJava 8 lambdas expressions
Java 8 lambdas expressions
Lars Lemos
 
Ad

Recently uploaded (20)

Nanometer Metal-Organic-Framework Literature Comparison
Nanometer Metal-Organic-Framework  Literature ComparisonNanometer Metal-Organic-Framework  Literature Comparison
Nanometer Metal-Organic-Framework Literature Comparison
Chris Harding
 
hypermedia_system_revisit_roy_fielding .
hypermedia_system_revisit_roy_fielding .hypermedia_system_revisit_roy_fielding .
hypermedia_system_revisit_roy_fielding .
NABLAS株式会社
 
PRIZ Academy - Functional Modeling In Action with PRIZ.pdf
PRIZ Academy - Functional Modeling In Action with PRIZ.pdfPRIZ Academy - Functional Modeling In Action with PRIZ.pdf
PRIZ Academy - Functional Modeling In Action with PRIZ.pdf
PRIZ Guru
 
ATAL 6 Days Online FDP Scheme Document 2025-26.pdf
ATAL 6 Days Online FDP Scheme Document 2025-26.pdfATAL 6 Days Online FDP Scheme Document 2025-26.pdf
ATAL 6 Days Online FDP Scheme Document 2025-26.pdf
ssuserda39791
 
Building-Services-Introduction-Notes.pdf
Building-Services-Introduction-Notes.pdfBuilding-Services-Introduction-Notes.pdf
Building-Services-Introduction-Notes.pdf
Lawrence Omai
 
Applications of Centroid in Structural Engineering
Applications of Centroid in Structural EngineeringApplications of Centroid in Structural Engineering
Applications of Centroid in Structural Engineering
suvrojyotihalder2006
 
Prediction of Flexural Strength of Concrete Produced by Using Pozzolanic Mate...
Prediction of Flexural Strength of Concrete Produced by Using Pozzolanic Mate...Prediction of Flexural Strength of Concrete Produced by Using Pozzolanic Mate...
Prediction of Flexural Strength of Concrete Produced by Using Pozzolanic Mate...
Journal of Soft Computing in Civil Engineering
 
Artificial intelligence and machine learning.pptx
Artificial intelligence and machine learning.pptxArtificial intelligence and machine learning.pptx
Artificial intelligence and machine learning.pptx
rakshanatarajan005
 
Efficient Algorithms for Isogeny Computation on Hyperelliptic Curves: Their A...
Efficient Algorithms for Isogeny Computation on Hyperelliptic Curves: Their A...Efficient Algorithms for Isogeny Computation on Hyperelliptic Curves: Their A...
Efficient Algorithms for Isogeny Computation on Hyperelliptic Curves: Their A...
IJCNCJournal
 
Lecture - 7 Canals of the topic of the civil engineering
Lecture - 7  Canals of the topic of the civil engineeringLecture - 7  Canals of the topic of the civil engineering
Lecture - 7 Canals of the topic of the civil engineering
MJawadkhan1
 
Parameter-Efficient Fine-Tuning (PEFT) techniques across language, vision, ge...
Parameter-Efficient Fine-Tuning (PEFT) techniques across language, vision, ge...Parameter-Efficient Fine-Tuning (PEFT) techniques across language, vision, ge...
Parameter-Efficient Fine-Tuning (PEFT) techniques across language, vision, ge...
roshinijoga
 
twin tower attack 2001 new york city
twin  tower  attack  2001 new  york citytwin  tower  attack  2001 new  york city
twin tower attack 2001 new york city
harishreemavs
 
Machine Learning basics POWERPOINT PRESENETATION
Machine Learning basics POWERPOINT PRESENETATIONMachine Learning basics POWERPOINT PRESENETATION
Machine Learning basics POWERPOINT PRESENETATION
DarrinBright1
 
sss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptx
sss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptx
sss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptx
ajayrm685
 
Agents chapter of Artificial intelligence
Agents chapter of Artificial intelligenceAgents chapter of Artificial intelligence
Agents chapter of Artificial intelligence
DebdeepMukherjee9
 
ML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdf
ML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdfML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdf
ML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdf
rameshwarchintamani
 
Novel Plug Flow Reactor with Recycle For Growth Control
Novel Plug Flow Reactor with Recycle For Growth ControlNovel Plug Flow Reactor with Recycle For Growth Control
Novel Plug Flow Reactor with Recycle For Growth Control
Chris Harding
 
Dynamics of Structures with Uncertain Properties.pptx
Dynamics of Structures with Uncertain Properties.pptxDynamics of Structures with Uncertain Properties.pptx
Dynamics of Structures with Uncertain Properties.pptx
University of Glasgow
 
Generative AI & Large Language Models Agents
Generative AI & Large Language Models AgentsGenerative AI & Large Language Models Agents
Generative AI & Large Language Models Agents
aasgharbee22seecs
 
Modelling of Concrete Compressive Strength Admixed with GGBFS Using Gene Expr...
Modelling of Concrete Compressive Strength Admixed with GGBFS Using Gene Expr...Modelling of Concrete Compressive Strength Admixed with GGBFS Using Gene Expr...
Modelling of Concrete Compressive Strength Admixed with GGBFS Using Gene Expr...
Journal of Soft Computing in Civil Engineering
 
Nanometer Metal-Organic-Framework Literature Comparison
Nanometer Metal-Organic-Framework  Literature ComparisonNanometer Metal-Organic-Framework  Literature Comparison
Nanometer Metal-Organic-Framework Literature Comparison
Chris Harding
 
hypermedia_system_revisit_roy_fielding .
hypermedia_system_revisit_roy_fielding .hypermedia_system_revisit_roy_fielding .
hypermedia_system_revisit_roy_fielding .
NABLAS株式会社
 
PRIZ Academy - Functional Modeling In Action with PRIZ.pdf
PRIZ Academy - Functional Modeling In Action with PRIZ.pdfPRIZ Academy - Functional Modeling In Action with PRIZ.pdf
PRIZ Academy - Functional Modeling In Action with PRIZ.pdf
PRIZ Guru
 
ATAL 6 Days Online FDP Scheme Document 2025-26.pdf
ATAL 6 Days Online FDP Scheme Document 2025-26.pdfATAL 6 Days Online FDP Scheme Document 2025-26.pdf
ATAL 6 Days Online FDP Scheme Document 2025-26.pdf
ssuserda39791
 
Building-Services-Introduction-Notes.pdf
Building-Services-Introduction-Notes.pdfBuilding-Services-Introduction-Notes.pdf
Building-Services-Introduction-Notes.pdf
Lawrence Omai
 
Applications of Centroid in Structural Engineering
Applications of Centroid in Structural EngineeringApplications of Centroid in Structural Engineering
Applications of Centroid in Structural Engineering
suvrojyotihalder2006
 
Artificial intelligence and machine learning.pptx
Artificial intelligence and machine learning.pptxArtificial intelligence and machine learning.pptx
Artificial intelligence and machine learning.pptx
rakshanatarajan005
 
Efficient Algorithms for Isogeny Computation on Hyperelliptic Curves: Their A...
Efficient Algorithms for Isogeny Computation on Hyperelliptic Curves: Their A...Efficient Algorithms for Isogeny Computation on Hyperelliptic Curves: Their A...
Efficient Algorithms for Isogeny Computation on Hyperelliptic Curves: Their A...
IJCNCJournal
 
Lecture - 7 Canals of the topic of the civil engineering
Lecture - 7  Canals of the topic of the civil engineeringLecture - 7  Canals of the topic of the civil engineering
Lecture - 7 Canals of the topic of the civil engineering
MJawadkhan1
 
Parameter-Efficient Fine-Tuning (PEFT) techniques across language, vision, ge...
Parameter-Efficient Fine-Tuning (PEFT) techniques across language, vision, ge...Parameter-Efficient Fine-Tuning (PEFT) techniques across language, vision, ge...
Parameter-Efficient Fine-Tuning (PEFT) techniques across language, vision, ge...
roshinijoga
 
twin tower attack 2001 new york city
twin  tower  attack  2001 new  york citytwin  tower  attack  2001 new  york city
twin tower attack 2001 new york city
harishreemavs
 
Machine Learning basics POWERPOINT PRESENETATION
Machine Learning basics POWERPOINT PRESENETATIONMachine Learning basics POWERPOINT PRESENETATION
Machine Learning basics POWERPOINT PRESENETATION
DarrinBright1
 
sss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptx
sss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptx
sss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptx
ajayrm685
 
Agents chapter of Artificial intelligence
Agents chapter of Artificial intelligenceAgents chapter of Artificial intelligence
Agents chapter of Artificial intelligence
DebdeepMukherjee9
 
ML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdf
ML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdfML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdf
ML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdf
rameshwarchintamani
 
Novel Plug Flow Reactor with Recycle For Growth Control
Novel Plug Flow Reactor with Recycle For Growth ControlNovel Plug Flow Reactor with Recycle For Growth Control
Novel Plug Flow Reactor with Recycle For Growth Control
Chris Harding
 
Dynamics of Structures with Uncertain Properties.pptx
Dynamics of Structures with Uncertain Properties.pptxDynamics of Structures with Uncertain Properties.pptx
Dynamics of Structures with Uncertain Properties.pptx
University of Glasgow
 
Generative AI & Large Language Models Agents
Generative AI & Large Language Models AgentsGenerative AI & Large Language Models Agents
Generative AI & Large Language Models Agents
aasgharbee22seecs
 

Heap and stack space in java

  • 1. MEMORY MANAGEMENT in JAVA STACK SPACE, HEAP SPACE AND STRING POOLS JAVATHLON.COM BY TALHA OCAKÇI
  • 2. MOTIVATION javathlon.com by Talha Ocakçı What happens when you run this code: A) Operating system fails. Because all memory is exhausted by our program. B) All running programs lose data since all memory is exhausted by our program. C) Operating system does not allow program execution by detecting the memory consumption. D) Program halts and throw an error.
  • 3. JVM MEMORY javathlon.com by Talha Ocakçı OPERATING SYSTEM MEMORY JVM MEMORY (CONSTANT) When main method is executed, JVM asks for some memory from the OS and size of this space can not be changed during the program execution.
  • 4. JVM MEMORY  Every object is stored in JVM memory and can be accessed by its address value.  A Java application can not interfere with a memory block outside the JVM. JAVATHLON.COM BY TALHA OCAKÇI
  • 5. Memory Management javathlon.com by Talha Ocakçı HEAP AREA STACK AREA NON-HEAP AREA Class instances and arrays Stacks for executing methods per thread Permanent Generation 1. Per-class data 2. Interned Strings
  • 6. HEAP AREA ▪ Objects (excluding interned strings) created in any thread are stored in this area. So this is a common place for all threads. ▪ Interned strings stored in non-heap area separately. javathlon.com by Talha Ocakçı
  • 7. HEAP AREA ▪ If you create an object with new() keyword, it will be stored in heap area. ▪If no reference left for a given object, it will be a candidate for garbage collection. javathlon.com by Talha Ocakçı
  • 9. MOTIVATION javathlon.com by Talha Ocakçı We will try to swap the customers and see if they were really swapped.
  • 10. WHAT IS STACK? Element 2 Element 1 Element 1 Element 2 Element 1 Element 1 JAVATHLON.COM BY TALHA OCAKÇI
  • 11. HOW IS METHOD ORDER PRESERVED? When a method is called, method-specific data is collected, tied together and put into stack space. It is removed when the execution is done. JAVATHLON.COM BY TALHA OCAKÇI
  • 13. STACK SPACE JVM uses this space for controlling the execution of methods.  Stores local values of ongoing methods.  Stores signatures of ongoing methods. JAVATHLON.COM BY TALHA OCAKÇI
  • 14. STACK AREA javathlon.com by Talha Ocakçı Stack for Thread 1 Stack for method A Stack for Thread 2 Stack frame per method Stack frame per method Stack frame per method Stack frame per method Stack area For each thread, a stack is stored. Each stack stores a stack frame per method call. Stack frame stores return type, arguments and address values of local objects and values of local primitive values.
  • 15. STACK FRAME Stored information Value Arguments String Local object (customer) 0x65899 Local primitive (age) 30 Return value True … JAVATHLON.COM BY TALHA OCAKÇI
  • 16. STACK FRAMES Located in a stack allocated to a thread in stack area. Stores 1. Address values of local objects 2. Values of local primitives 3. Return value of the method 4. Current class’s definition’s address value 5. Operands stack javathlon.com by Talha Ocakçı
  • 17. MOTIVATION javathlon.com by Talha Ocakçı What happens when you run this code? A) Prints 5 infinitely B) Exhausts all the memory of JVM C) Throws an exception
  • 18. MOTIVATION javathlon.com by Talha Ocakçı Stack space is limited. Here, without popping a stack frame from the stack, a new one is pushed. So allocated memory for method information grows rapidly. JVM throws a StackOverflowException and halts the execution.
  • 19. PASSING OBJECTS in JAVA javathlon.com by Talha Ocakçı In Java, objects are passed between methods by their values. 1. Objects are passed by values of their address on heap space 2. Primitives are passed by values 3. Strings are also passed by values of their value. This value is checked against the interned strings in non-heap area.
  • 20. EXAMPLE javathlon.com by Talha Ocakçı We will try to swap the customers and See if they were really swapped.
  • 21. javathlon.com by Talha Ocakçı ... HEAP SPACE 1 Talha Turkey 2 John US customer1 1000 customer2 2000 1000 2000 Stack frame for main method public void swapCustomers(Customer cust1, Customer cust2) { Customer temp = cust2; cust2 = cust1; cust1 = temp; }
  • 22. javathlon.com by Talha Ocakçı ... HEAP SPACE 1 Talha Turkey 2 John US customer1 1000 customer2 2000 1000 2000 Stack frame for main method public void swapCustomers(Customer cust1, Customer cust2) { Customer temp = cust2; cust2 = cust1; cust1 = temp; } cust1 1000 cust2 2000 Stack frame for swapCustomers method
  • 23. javathlon.com by Talha Ocakçı ... HEAP SPACE 1 Talha Turkey 2 John US customer1 1000 customer2 2000 1000 2000 Stack frame for main method public void swapCustomers(Customer cust1, Customer cust2) { Customer temp = cust2; cust2 = cust1; cust1 = temp; } temp 2000 cust1 1000 cust2 2000 Stack frame for swapCustomers method
  • 24. javathlon.com by Talha Ocakçı ... HEAP SPACE 1 Talha Turkey 2 John US customer1 1000 customer2 2000 1000 2000 Stack frame for main method public void swapCustomers(Customer cust1, Customer cust2) { Customer temp = cust2; cust2 = cust1; cust1 = temp; } temp 2000 cust1 1000 cust2 1000 Stack frame for swapCustomers method
  • 25. javathlon.com by Talha Ocakçı ... HEAP SPACE 1 Talha Turkey 2 John US customer1 1000 customer2 2000 1000 2000 Stack frame for main method public void swapCustomers(Customer cust1, Customer cust2) { Customer temp = cust2; cust2 = cust1; cust1 = temp; } temp 2000 cust1 2000 cust2 1000 Stack frame for swapCustomers method
  • 26. javathlon.com by Talha Ocakçı ... HEAP SPACE 1 Talha Turkey 2 John US customer1 1000 customer2 2000 1000 2000 Stack frame for main method public void swapCustomers(Customer cust1, Customer cust2) { Customer temp = cust2; cust2 = cust1; cust1 = temp; } temp 2000 cust1 2000 cust2 1000 Stack frame for swapCustomers method
  • 27. javathlon.com by Talha Ocakçı ... HEAP SPACE 1 Talha Turkey 2 John US customer1 1000 customer2 2000 1000 2000 Stack frame for main method public void swapCustomers(Customer cust1, Customer cust2) { Customer temp = cust2; cust2 = cust1; cust1 = temp; } So nothing has been changed on Customer1 and customer2 references.
  • 28. SECOND EXAMPLE javathlon.com by Talha Ocakçı We will pass the object to a method, change some attributes of it and check whether the original object has been changed.
  • 29. javathlon.com by Talha Ocakçı ... HEAP SPACE 1 Talha Turkey customer1 1000 1000 Stack frame for main method public void changeCountry(Customer cust) { cust.address = "new zealand"; }
  • 30. javathlon.com by Talha Ocakçı ... HEAP SPACE 1 Talha Turkey customer1 1000 1000 Stack frame for main method public void changeCountry(Customer cust) { cust.address = "new zealand"; } cust 1000
  • 31. javathlon.com by Talha Ocakçı ... HEAP SPACE 1 Talha new zealand customer1 1000 1000 Stack frame for main method public void changeCountry(Customer cust) { cust.address = "new zealand"; } cust 1000 Stack frame for changeCountry method
  • 32. javathlon.com by Talha Ocakçı ... HEAP SPACE 1 Talha new zealand customer1 1000 1000 Stack frame for main method public void changeCountry(Customer cust) { cust.address = "new zealand"; } So, the original object is really modified on heap space
  • 33. EXAMPLE 3 javathlon.com by Talha Ocakçı We will send a primitive to a method, multiply the argument value and will check Whether te original value has been changed.
  • 34. javathlon.com by Talha Ocakçı ... HEAP SPACE x 10 Stack frame for main method public void doubleTheValue(int value) { value = value *2; } Since there is no object defined, no object exists for this program value 10 Stack frame for doubleTheValue method
  • 35. javathlon.com by Talha Ocakçı ... HEAP SPACE x 10 Stack frame for main method public void doubleTheValue(int value) { value = value *2; } Since there is no object defined, no object exists for this program value 20 Stack frame for doubleTheValue method
  • 36. javathlon.com by Talha Ocakçı ... HEAP SPACE x 10 Stack frame for main method public void doubleTheValue(int value) { value = value *2; } Since there is no object defined, no object exists for this program
  • 37. Example 4 javathlon.com by Talha Ocakçı Now we will try the same thing with a String. We will demonstrate the special case of the String class and string interning idea.
  • 38. Example 4 javathlon.com by Talha Ocakçı This code will output «current». Because updateValue method could not change the value of String string variable The reason is string interning also known as «string pooling».
  • 39. Lets start with an example javathlon.com by Talha Ocakçı What is the output of this code snippet?
  • 40. Lets start with an example javathlon.com by Talha Ocakçı If you answered this as «true», you probably know what is going on.
  • 41. Second example javathlon.com by Talha Ocakçı What is the output of this code snippet?
  • 42. Second example javathlon.com by Talha Ocakçı Answer is «false»
  • 43. Third example javathlon.com by Talha Ocakçı Now, let’s try it with string interning. Output is true. Now lets inspect what is going on.
  • 44. String interning One of the most used method in an ordinary program is string comparison. And in an average program, there are so many strings which has an average length between 10-20. So, to compare two strings, JVM must compare that much character everytime causing a real performance problem. That’s why, JVM puts a used String to a String pool and uses the internal HashMap for comparing the string variables. javathlon.com by Talha Ocakçı
  • 45. javathlon.com by Talha Ocakçı ... STRING POOL s1 6000 s2 6000 Stack frame for main method String s1 = "talha_ocakci"; talha_ocakci 6000 String s2 = "talha_ocakci";
  • 46. javathlon.com by Talha Ocakçı ... STRING POOL s1 6000 s2 6000 Stack frame for main method String s1 = "talha_ocakci"; talha_ocakci 6000 String s2 = "talha_ocakci"; s1 == s2 6000 == 6000 true
  • 47. javathlon.com by Talha Ocakçı STRING POOL s3 9500 s4 9600 Stack frame for main method String s3 = new String("talha_ocakci"); String s4 = new String("talha_ocakci"); ... talha_ocakci 6000 HEAP ... talha_ocakci 9500 talha_ocakci 9600
  • 48. javathlon.com by Talha Ocakçı STRING POOL s3 9500 s4 9600 Stack frame for main method String s3 = new String("talha_ocakci"); s3 = s3.intern(); String s4 = new String("talha_ocakci"); s4= s4.intern(); ... talha_ocakci 6000 HEAP ... talha_ocakci 9500 talha_ocakci 9600
  • 49. javathlon.com by Talha Ocakçı STRING POOL s3 6000 s4 6000 Stack frame for main method String s3 = new String("talha_ocakci"); s3 = s3.intern(); String s4 = new String("talha_ocakci"); s4= s4.intern(); ... talha_ocakci 6000 HEAP ... talha_ocakci 9500 talha_ocakci 9600
  翻译: