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

Slides:



Advertisements
Similar presentations
Ade Azurat, Advanced Programming 2004 (Based on LYS Stefanus’s slides) Advanced Programming 2004, Based on LYS Stefanus’s slides Slide 2.1 Multithreading.
Advertisements

Unit 141 Threads What is a Thread? Multithreading Creating Threads – Subclassing java.lang.Thread Example 1 Creating Threads – Implementing java.lang.Runnable.
Algorithm Programming Concurrent Programming in Java Bar-Ilan University תשס"ח Moshe Fresko.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L19 (Chapter 24) Multithreading.
CS220 Software Development Lecture: Multi-threading A. O’Riordan, 2009.
1 Threads (Part I) Introduction to Threads and Concurrency Overview  Introduction to Threads of Computation  Creating Threads in java an Example  Thread.
ThreadThread Thread Basics Thread Synchronization Animations.
Definitions Process – An executing program
Multithreading in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Threads Just Java: C10–pages 251- C11–pages 275-
Multithreading in Java Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
© Andy Wellings, 2004 Roadmap  Introduction  Concurrent Programming  Communication and Synchronization  Completing the Java Model  Overview of the.
Lecture 4 : JAVA Thread Programming
Chapter 15 Multithreading F Threads Concept  Creating Threads by Extending the Thread class  Creating Threads by Implementing the Runnable Interface.
Java Programming: Advanced Topics
Lecture 5 : JAVA Thread Programming Courtesy : MIT Prof. Amarasinghe and Dr. Rabbah’s course note.
Quick overview of threads in Java Babak Esfandiari (extracted from Qusay Mahmoud’s slides)
Today’s Agenda  Quick Review  Finish Java Threads  The CS Problem Advanced Topics in Software Engineering 1.
Concurrent Programming in Java Dr. Zoltan Papp. Motivation: event driven, responsive systems Sequential approach: while ( true ) { do event = getEventId()
1 Tutorial: CSI 3310 Dewan Tanvir Ahmed SITE, UofO.
Dr. R R DOCSIT, Dr BAMU. Basic Java : Multi Threading 2 Objectives of This Session State what is Multithreading. Describe the life cycle of Thread.
Threads Concurrency in Java. What is mult-tasking? Doing more than one task.
111 © 2002, Cisco Systems, Inc. All rights reserved.
Java Threads. What is a Thread? A thread can be loosely defined as a separate stream of execution that takes place simultaneously with and independently.
Threading Eriq Muhammad Adams J
Threads.
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
Introduction to Threads Session 01 Java Simplified / Session 14 / 2 of 28 Objectives Define a thread Define multithreading List benefits of multithreading.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 18 Advanced Java Concepts Threads and Multithreading.
In Java processes are called threads. Additional threads are associated with objects. An application is associated with an initial thread via a static.
What is a ‘ thread ’ ? Free Online Dictionary of Computing (FOLDOC) Sharing a single CPU between multiple tasks (or "threads") in a way designed to minimize.
Multithreading in JAVA
Object-oriented Programming in Java. © Aptech Ltd. Introduction to Threads/Session 7 2  Introduction to Threads  Creating Threads  Thread States 
Li Tak Sing COMPS311F. Threads A thread is a single sequential flow of control within a program. Many programming languages only allow you to write programs.
15.1 Threads and Multi- threading Understanding threads and multi-threading In general, modern computers perform one task at a time It is often.
© Wang Bin 2004 Java Threads. © Wang Bin 2004 In this lesson, you will learn to: u Define the concepts of threads and multithreading  Identify the functions.
Multi-Threading in Java
Multithreaded programming  Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run.
Parallel Processing (CS526) Spring 2012(Week 8).  Shared Memory Architecture  Shared Memory Programming & PLs  Java Threads  Preparing the Environment.
Threads in Java Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without.
Thread A thread represents an independent module of an application that can be concurrently execution With other modules of the application. MULTITHREADING.
Multithreading and Garbage Collection Session 16.
1 Java Programming Java Programming II Concurrent Programming: Threads ( I)
Multithreading. Multitasking The multitasking is the ability of single processor to perform more than one operation at the same time Once systems allowed.
Java Threads Lilin Zhong. Java Threads 1. New threads 2. Threads in the running state 3. Sleeping threads and interruptions 4. Concurrent access problems.
Threads b A thread is a flow of control in a program. b The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.
Chapter 13: Multithreading The Thread class The Thread class The Runnable Interface The Runnable Interface Thread States Thread States Thread Priority.
Concurrency (Threads) Threads allow you to do tasks in parallel. In an unthreaded program, you code is executed procedurally from start to finish. In a.
1 Threads in Java Jingdi Wang. 2 Introduction A thread is a single sequence of execution within a program Multithreading involves multiple threads of.
Concurrency in Java MD. ANISUR RAHMAN. slide 2 Concurrency  Multiprogramming  Single processor runs several programs at the same time  Each program.
SCJP 9/10 Threads.
Multithreading / Concurrency
Multithreading Lec 23.
Chapter 13: Multithreading
Multi Threading.
Java Multithreading.
Threads Chate Patanothai.
Definitions Concurrent program – Program that executes multiple instructions at the same time. Process – An executing program (the running JVM for Java.
Java Concurrency.
Multithreading.
Java Based Techhnology
Multithreading.
برنامه‌نویسی چندنخی Multi-Thread Programming
Chapter 15 Multithreading
Computer Science 2 06A-Java Multithreading
Multithreading in java.
Threads and Multithreading
Concurrent programming
CMSC 202 Threads.
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

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