From Theory to Practice 2 OOP 2006. Overview Performance issues: –Preparing classes for inheritance –Memory management and release of obsolete object.

Slides:



Advertisements
Similar presentations
Chapter 22 Implementing lists: linked implementations.
Advertisements

Introduction to Java 2 Programming Lecture 3 Writing Java Applications, Java Development Tools.
COMP 121 Week 9: AbstractList and ArrayList. Objectives List common operations and properties of Lists as distinct from Collections Extend the AbstractCollection.
1 Todays Objectives Announcements Homework #1 is due next week Return Quiz 1 – answers are posted on the Yahoo discussion page site Basic Java Programming.
Java Programming 2 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in PGDCA 203:Object Technology, S P University.
Topic 10 Java Memory Management. 1-2 Memory Allocation in Java When a program is being executed, separate areas of memory are allocated for each class.
Chapter 5 Queues Modified. Chapter Scope Queue processing Comparing queue implementations 5 - 2Java Software Structures, 4th Edition, Lewis/Chase.
CSC 205 – Java Programming II Lecture 25 March 8, 2002.
1 Maximize Java Performance by using YOURKIT with uPortal development Faizan Ahmed – Sr. Application Developer.
Inheritance Inheritance Reserved word protected Reserved word super
CS 106 Introduction to Computer Science I 05 / 03 / 2010 Instructor: Michael Eckmann.
Arrays An array is a collection of variables, all of the same type. An array is created with the new operator. The size of an array must be specified at.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Principles of Object-Oriented Software Development The language Java.
Scott Grissom, copyright 2004Ch 3: Java Features Slide 1 Why Java? It is object-oriented provides many ready to use classes platform independent modern.
Unit 291 Java Collections Framework: Interfaces Introduction to the Java Collections Framework (JCF) The Comparator Interface Revisited The Collection.
Data Abstraction and Object- Oriented Programming CS351 – Programming Paradigms.
Cmp Sci 187: Midterm Review Based on Lecture Notes.
From Theory to Practice 1 OOP Overview Reminder – some OOD principles from previous lessons: –Class Inheritance vs. Object Composition –Program.
Interfaces and Inner Classes. What is an Interface?  What is “presented to the user”?  The public part of a class?  What is the substance of an interface?
OOP in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
OOP Languages: Java vs C++
3.1 Documentation & Java Language Elements Purpose of documentation Assist the programmer with developing the program Assist other programers who.
Programming Languages and Paradigms Object-Oriented Programming.
Overview of Previous Lesson(s) Over View  OOP  A class is a data type that you define to suit customized application requirements.  A class can be.
Topic 3 The Stack ADT.
FEN 2012 UCN Technology: Computer Science1 C# - Introduction Language Fundamentals in Brief.
Object Oriented Programming: Java Edition By: Samuel Robinson.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
CSC Programming I Lecture 8 September 9, 2002.
Effective Java: Creating and Destroying Objects Last Updated: Fall 2012.
ArrayList, Multidimensional Arrays
Copyright © 2002, Systems and Computer Engineering, Carleton University Hashtable.ppt * Object-Oriented Software Development Unit 8.
Constructors CMSC 202. Object Creation Objects are created by using the operator new in statements such as… The following expression invokes a special.
30 May Stacks (5.1) CSE 2011 Winter Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An.
1/20/03A2-1 CS494 Interfaces and Collection in Java.
Page: 1 การโปรแกรมเชิงวัตถุด้วยภาษา JAVA บุรินทร์ รุจจนพันธุ์.. ปรับปรุง 15 มิถุนายน 2552 Keyword & Data Type มหาวิทยาลัยเนชั่น.
Lecture 10 Concepts of Programming Languages Arne Kutzner Hanyang University / Seoul Korea.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
CS170 ygao JAVA, C4Slide 1. CS170 ygao JAVA, C4Slide 2.
OOP using C Abstract data types How to accomplish the task??? Requirements Details Input, output, process Specify each task in terms of input.
SOEN 343 Software Design Section H Fall 2006 Dr Greg Butler
Computer Science 209 Software Development Inheritance and Composition.
Session 6 Comments on Lab 3 & Implications of Inheritance.
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
PROGRAMMING PRE- AND POSTCONDITIONS, INVARIANTS AND METHOD CONTRACTS B MODULE 2: SOFTWARE SYSTEMS 13 NOVEMBER 2013.
Classes, Interfaces and Packages
IMPLEMENTING ARRAYLIST COMP 103. RECAP  Comparator and Comparable  Brief look at Exceptions TODAY  Abstract Classes - but note that the details are.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Reference Types CSE301 University of Sunderland Harry R Erwin, PhD.
Internet Computing Module II. Syllabus Creating & Using classes in Java – Methods and Classes – Inheritance – Super Class – Method Overriding – Packages.
Implementing ArrayList Part T2 Lecture 6 School of Engineering and Computer Science, Victoria University of Wellington  Thomas Kuehne, Marcus Frean,
19-Mar-16 Collections and ArrayLists.. 2 Collections Why use Collections. Collections and Object-Orientation. ArrayLists. Special Features. Creating ArrayLists.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Modern Programming Tools And Techniques-I
Java Memory Management
Module 9: Memory and Resource Management
Java Memory Management
Memory leaks in Java? Not exactly memory leak
Implementing ArrayList Part 1
Pointers Revisited What is variable address, name, value?
Constructors CMSC 202.
Constructor Overloading
null, true, and false are also reserved.
Programming in Java Lecture 11: ArrayList
Assessment – Java Basics: Part 1
Variables and Java vs C++
Lecture 10 Concepts of Programming Languages
Classes and Objects Object Creation
CMSC 202 Constructors Version 9/10.
Presentation transcript:

From Theory to Practice 2 OOP 2006

Overview Performance issues: –Preparing classes for inheritance –Memory management and release of obsolete object references The sources for this lecture: –Effective Java™ by Joshua Bloch The book contains many rules of thumb for writing a code that is clear, correct, robust and reuseable Most code samples are taken from / / –About garbage collection:

Preparing Classes For Inheritance Design and document for inheritance or else prohibit it. What does it mean? Document precisely the effect of overriding any method Choose protected methods judiciously Constructors and clone must not involve overridable methods Special measures should be taken when implementing Serializable objects

Documentation remove public boolean remove(Object o) Removes a single instance of the specified element from this collection, if it is present (optional operation). More formally, removes an element e such that (o==null ? e==null : o.equals(e)), if the collection contains one or more such elements. Returns true if the collection contained the specified element (or equivalently, if the collection changed as a result of the call).This implementation iterates over the collection looking for the specified element. If it finds the element, it removes the element from the collection using the iterator's remove method. Note that this implementation throws an UnsupportedOperationException if the iterator returned by this collection's iterator method does not implement the remove method and this collection contains the specified object. A description of the effect of overriding a method in AbstractCollection

Choosing Protected Methods Consider the API of abstractList The following method is called by clear Allows efficient implementation of clear in inherited class List subList(int fromIndex, int toIndex) Returns a view of the portion of this list between fromIndex, inclusive, and toIndex, exclusive. void clear() Removes all of the elements from this collection (optional operation). protected void removeRange(int fromIndex, int toIndex) Removes from this list all of the elements whose index is between fromIndex, inclusive, and toIndex, exclusive.

Constructors What happens if the constructor invokes overridable method? public class Super { // Broken - constructor invokes overridable method public Super() { m(); } public void m() { }

Constructors final class Sub extends Super { // Blank final, set by constructor private final Date date; Sub() { date = new Date(); } // Overrides Super.m, invoked by the constructor Super() public void m() { System.out.println(date); } public static void main(String[] args) { Sub s = new Sub(); s.m(); } The program prints null

Memory Management in Java The memory in java is handled in two main structures: –Program execution stack: contains the memory required by method invocation –The memory heap: contains the memory required by objects in the program The new command allocates memory for an object and activates its constructor

Releasing Unused Objects Memory release of unreferenced objects is handled using garbage collection The garbage collector: –Identify objects that are no-longer in use –Recycle memory occupied by such objects An object is in use if it can be accessed or reached by the program in its current state In order to define a reachable object we first define the root set of references

The Root Set and Reachable Objects The root set of references includes: –References to objects in active methods of the program: Method arguments Local variables –Static reference variables –References reiterated through the Java Native Interface (JNI) An object is reachable if –It is referenced by a reference from the root set –It is referenced by another reachable object

The Root Set and Reachable Objects Root set of references Unreachable objects (garbage) Reachable objects Java Heap

Advantage of Garbage collected Heap In programming languages such as C and C++, the programmer manages memory allocation and release In Java, the programmer does not have to deal with memory allocation But special care should be taken to avoid memory leaks – where not-used objects still occupy memory

Example – Stack Implementation public class Stack { private Object[] elements; private int size = 0; public Stack(int initialCapacity) { this.elements = new Object[initialCapacity]; } public void push(Object e) { ensureCapacity(); elements[size++] = e; } private void ensureCapacity() { if (elements.length == size) { Object[] oldElements = elements; elements = new Object[2 * elements.length + 1]; System.arraycopy(oldElements, 0, elements, 0, size); }

Stack Implementation - continue // Can you spot the memory leak? public Object pop() { if (size==0) throw new EmptyStackException(); Object result = elements[--size]; return result; } If the stack shrinks, objects that were popped of the stack will not be garbage collected Memory leak potential consequences –Reduced performance due to paging or increased garbage collection activity –OutOfMemoryError

Solution public Object pop() { if (size==0) throw new EmptyStackException(); Object result = elements[--size]; // Eliminate obsolete reference elements[size] = null; return result; }

Correct Memory handling Memory leaks are hard to detect and resolved (there are specialized tools for that) Null out object references in classes that manage their own memory Special care should also be taken for caches Do not null out every object finishing its role: –References of local variables fall out of scope –Variable reuse releases the previous referenced objects Define each variable in the narrowest possible score (There are other good reasons to do it, what are they?)