Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 5.0 Garbage collector & Threads : Overview Introduction: In this module we discuss the merits and demerits of automated garbage collection over manual.

Similar presentations


Presentation on theme: "1 5.0 Garbage collector & Threads : Overview Introduction: In this module we discuss the merits and demerits of automated garbage collection over manual."— Presentation transcript:

1 1 5.0 Garbage collector & Threads : Overview Introduction: In this module we discuss the merits and demerits of automated garbage collection over manual garbage collection. We see how Java defines it’s garbage collector. We also look into how we can make objects eligible for garbage collection. Understanding the behavior of garbage collector is crucial to the development of efficient code. Another major topic we discuss here is Multithreaded programming in Java. Java is one of few languages that have inbuilt support for Threads, which we are going to explore. Also here, we will discuss the major points attached to multithreaded programming like locks / moniters and synchronization.

2 2 5.0 Garbage collector & Threads : Overview Objectives: After completing this Topic, you will be able to understand the concepts of garbage collection and threads, and write multithreaded programs in Java. 1.Understanding Garbage collection. 2.Understanding the concept of threads. 3.Defining and Running Threads. 4.Thread Life cycle. 5.Methods : sleep(), yield() and join(). 6.Synchronizing Threads. 7.Thread Groups. 8.Daemon threads.

3 3 Understanding Garbage collection Overview of Memory Management and Garbage Collection Objects are dynamically allocated by using the new operator. Manual memory management in languages like C++. –Memory leaks. Java takes a different approach : “Garbage Collection”. Overview of Garbage Collection. –The Heap : part of memory where Java objects live. –Concept of an object being “reachable”. –When Does the Garbage Collector Run? –How Does the Garbage Collector Work? –Can a Java application run out of memory?

4 4 Writing Code to Explicitly make Objects Eligible for Collection Nulling a Reference public class GarbageTruck { public static void main(String [] args) { StringBuffer sb = new StringBuffer("hello"); System.out.println(sb); /*The StringBuffer object is not eligible for collection*/ sb = null; /*Now the StringBuffer object is eligible for collection*/ } Understanding Garbage collection

5 5 Writing Code to Explicitly make Objects Eligible for Collection Reassigning a Reference Variable. public class GarbageCollector { public static void main(String [] args) { StringBuffer sb = new StringBuffer("hello"); StringBuffer sb1 = new StringBuffer(“World"); System.out.println(sb +” “+ sb1); /*The StringBuffer “Hello” is not eligible for collection*/ sb = sb1; // sb now points to StringBuffer “World” /*The StringBuffer “Hello” is eligible for collection*/ } Understanding Garbage collection

6 6 Writing Code to Explicitly make Objects Eligible for Collection Isolating a Reference. public class Island { Island i; public static void main(String [] args) { Island i1 = new Island(); Island i2 = new Island(); i1.i = i2; // i1 refers to i2 i2.i = i1; // i2 refers to i1 i1 = null; i2 = null; /*An island of isolated objects created*/ } Understanding Garbage collection

7 7 Ask for garbage collection Runtime class Every Java application has a single instance of class Runtime that allows the application to interface with the environment in which the application is running. The current runtime can be obtained from the getRuntime method. One way to ask for garbage collection: Runtime rt = Runtime.getRuntime(); rt.gc(); The simplest way to ask for garbage collection System.gc(); // an alternative to rt.gc() Understanding Garbage collection

8 8 Cleaning Up Before Garbage Collection The Finalize() Method –Defined in class Object.  The general form of finalize method protected void finalize() throws Throwable{ //finalization code } –Any code that you put into your class’s overridden finalize()method is not guaranteed to run. Concepts concerning finalize() : –For any given object, finalize() will be called only once by the garbage collector. –Calling finalize() can actually result in saving an object from deletion.  Code in finalizer some_Method(this); –Overriden finalizers are not implicitly chained. protected void finalize() throws Throwable { //finalizer code here super.finalize(); } Understanding Garbage collection

9 9 Understanding the concept of threads What is Multitasking? –Process based Multitaking. –Thread based multitasking.  What are threads?  Introduction to the concept of Multithreading. Java provides built-in support for multithreaded programming. –Important classes/interfaces java.lang.Runnable java.lang.Thread java.lang.ThreadGroup Threads : The Java Way In Java, “thread” means two different things –An instance of class java.lang.Thread –A thread of execution When it comes to threads, very little is guaranteed. –Every JVM has its own way to run the Thread.

10 10 Defining and Running Threads Making a thread –Method run() public void run() { //job code goes here } –Relationship between Interface Runnable and class Thread. –You can define and instantiate a thread in one of two ways. Extend the java.lang.Thread class. Implement the Runnable interface. interface Runnable{ public void run(); } Interface : Runnable Class : Thread Implemented by Fig 5.1

11 11 Extend the java.lang.Thread class The simplest way to define code to run in a separate thread is to – Extend the Thread class. – Override the run() method. class MyThread extends Thread { //1 public void run() { //2 System.out.println(“Job running in MyThread"); //3 } class RunningThread{ public static void main(String args[]){ MyThread t = new MyThread(); //4 t.start(); //5 } Defining and Running Threads

12 12 Implement the Runnable interface Contructors you can use for this contain Runnable object as one argument. –Example : Thread(Runnable target) class MyRunnable implements Runnable { //1 public void run() { //2 System.out.println(“Job running in MyThread"); //3 } class RunningThread{ public static void main(String args[]){ MyRunnable r = new MyRunnable(); //4 Thread t = new Thread(r); //5 t.start(); } Defining and Running Threads

13 13 Thread Life cycle Thread Scheduler. –The order in which runnable threads are chosen to run is not guaranteed. Thread States. –New. –Runnable. –Running. –Waiting/Blocking/Sleeping –Dead. Fig 5.2

14 14 Methods : sleep(), yield() and join() Method sleep. –Two overloaded versions.  public static void sleep(long millis) throws InterruptedException  public static void sleep(long millis, int nanos) throws InterruptedException class MyRunnable_1 implements Runnable{ //1 public void run() { //2 try { Thread.sleep(5*60*1000); //3 } catch (InterruptedException ex) { } System.out.println(“After a minimum of 5 minutes”); //4 } class RunningThread{ public static void main(String args[]){ MyRunnable_1 r = new MyRunnable_1(); //5 new Thread(r).start(); //6} }

15 15 Method yield. –Concept of thread priority.  The three static final variables that define the range of thread priorities Thread.MIN_PRIORITY (1) Thread.NORM_PRIORITY (5) Thread.MAX_PRIORITY (10)  A thread gets a default priority that is the priority of the thread of execution that creates it.  Method : public final void setPriority(int newPriority) Example MyRunnable r = new MyRunnable(); Thread t = new Thread(r); t.setPriority(Thread.MIN_PRIORITY); t.start(); –public static void yield() Example MyRunnable r = new MyRunnable(); Thread t = new Thread(r); t.start(); /*code here*/ Thread.yield();//for turn-taking between equal-priority threads Methods : sleep(), yield() and join()

16 16 Method join. – public final void join() throws InterruptedException – public final void join(long millis) throws InterruptedException – public final void join(long millis,int nanos)throws InterruptedException class MyThread_1 extends Thread { public void run() { System.out.println(“To join into main Thread"); } Class ThreadRunning{ public static void main(String args[]){ MyThread_1 t = new MyThread_1(); t.start(); //1 t.join(); //2 System.out.println(“Thread join complete”); //3 } Methods : sleep(), yield() and join()

17 17 Synchronizing Threads Need of synchronization. –Producer-consumer problem. How does synchronization work : Concept of Lock. –How to synchronize code ?  Synchronized method public synchronized void methodName() { /*code here*/ }  Synchronized Block synchronized (lock){ /*code here*/ } –Key points about locking and synchronization  Only methods can be synchronized, not variables.  Each object has just one lock.  Static method can be synchronized.  Not all methods in a class must be synchronized. multiple threads can access the nonsynchronized methods of the class.  Only one thread can be accessing one of the synchronized methods in a class.  If a thread goes to sleep, it takes its locks with it.  A thread can acquire more than one lock.  Concept of Deadlock

18 18 public class SynchronizedAccess{ private int content; public synchronized int getContent() { return (content); } public synchronized void putContent(int value) { content = value; } public void synchronizeBlock(int value){ synchronized(this){ content++; } /* some other code */ } Synchronizing Threads

19 19 Thread communication –wait() (Class Object) –notify() (Class Object) –notifyAll() (Class Object) class ThreadA { public static void main(String[] args) throws Exception { ThreadB b = new ThreadB(); synchronized(b) { //1 b.start(); //2 System.out.println(“Before b"); b.wait(); //3 } System.out.println(“val:"+ b.val);//4 } class ThreadB extends Thread { int val=0; public void run() { synchronized(this) { val = 100; //5 notify(); //6 } wait(), notify(), and notifyAll() must be called from within a synchronized context! Synchronizing Threads

20 20 Thread Groups Default thread group and System thread group. Reason behind thread groups. ThreadGroup class. public class TestAccess { public static void main(String[] args) { ThreadGroup x =new ThreadGroup("x"), y =new ThreadGroup(x, "y");//1 Thread one = new Thread(y, "one"); //2 x.setMaxPriority(Thread.MAX_PRIORITY-2); //3 one.setPriority(Thread.MAX_PRIORITY); //4 x.list(); //5 } /*OUTPUT : java.lang.ThreadGroup[name=x,maxpri=8] java.lang.ThreadGroup[name=y,maxpri=8] Thread[one,8,y] */

21 21 Daemon threads Provide a general service in the background. When all of the non-daemon threads complete, the program is terminated. public final boolean isDaemon() public final void setDaemon(boolean on) class MyThread_2 extends Thread{ public void run(){ System.out.println("Daemon"); //1 } public class DaemonMaker{ public static void main(String[] args){ MyThread_2 m= new MyThread_2(); m.setDaemon(true); //2 m.start(); //3 }

22 22 Garbage collector & Threads : Summary The Heap is the part of memory where Java objects live. The garbage collector attempts to remove objects from memory when they are not used. We cannot make the garbage collector run. It is completely the JVM’s decision. Method finalize() can be used to cleanup before the object is garbage collected. Java provides built-in support for multithreaded programming. There are two ways to define code to be run in a separate thread –Extend Thread class. –Implement Runnable. A thread can be in one of the five states: New, Runnable, Running, Waiting/blocked/sleeping, Dead. You can use sleep() to slow a thread down by forcing it to go into a sleep mode..

23 23 Garbage collector & Threads : Summary The nonstatic join() method lets one thread “join onto the end” of another thread. The intention to use yield() is to promote turn-taking among equal-priority threads. You can synchronize a method or a block of code. wait(), notify(), and notifyAll() help threads communicate. All thread groups will ultimately have the system thread group as the parent. Daemon threads provide a general service in the background


Download ppt "1 5.0 Garbage collector & Threads : Overview Introduction: In this module we discuss the merits and demerits of automated garbage collection over manual."

Similar presentations


Ads by Google