Programming Design Patterns

Slides:



Advertisements
Similar presentations
Chapter 5: The Singleton Pattern
Advertisements

Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
ITEC200 – Week03 Inheritance and Class Hierarchies.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Road Map Introduction to object oriented programming. Classes
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Threads A thread is a program unit that is executed independently of other parts of the program A thread is a program unit that is executed independently.
Programming Languages and Paradigms Object-Oriented Programming.
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Design patterns. What is a design pattern? Christopher Alexander: «The pattern describes a problem which again and again occurs in the work, as well as.
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.
111 © 2002, Cisco Systems, Inc. All rights reserved.
Inheritance in the Java programming language J. W. Rider.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Programming in Java CSCI-2220 Object Oriented Programming.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Java Thread and Memory Model
The Singleton Pattern SE-2811 Dr. Mark L. Hornick 1.
Classes. Constructor A constructor is a special method whose purpose is to construct and initialize objects. Constructor name must be the same as the.
CS170 ygao JAVA, C4Slide 1. CS170 ygao JAVA, C4Slide 2.
Chapter 5 Introduction to Defining Classes
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Threads and Singleton. Threads  The JVM allows multiple “threads of execution”  Essentially separate programs running concurrently in one memory space.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Classes, Interfaces and Packages
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
YG - CS Concept of Encapsulation What is encapsulation? - data and functions/methods are packaged together in the class normally.
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.
Internet Computing Module II. Syllabus Creating & Using classes in Java – Methods and Classes – Inheritance – Super Class – Method Overriding – Packages.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
Java Thread Programming
The Object-Oriented Thought Process Chapter 03
Copyright © Jim Fawcett Spring 2017
Data Abstraction: The Walls
Threads in Java Two ways to start a thread
Multithreading / Concurrency
JAVA MULTIPLE CHOICE QUESTION.
Multi Threading.
Static data members Constructors and Destructors
Chapter 11 Inheritance and Polymorphism
CSE 501N Fall ‘09 21: Introduction to Multithreading
Inheritance and Polymorphism
The Singleton Pattern SE-2811 Dr. Mark L. Hornick.
Java Programming Language
Lecture 25 More Synchronized Data and Producer/Consumer Relationship
Chapter 3: Using Methods, Classes, and Objects
Inheritance in Java.
Chapter 3 Assignment Statement
Object Based Programming
Chapter 9 Inheritance and Polymorphism
Java Programming Language
Object Oriented Programming in java
More Object-Oriented Programming
Java Concurrency 17-Jan-19.
Objects Managing a Resource
Object Oriented Programming in java
Java Concurrency.
Web Design & Development Lecture 4
Java Concurrency.
Threads and Multithreading
Java Concurrency 29-May-19.
CSE 332: Concurrency and Locks
More concurrency issues
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Threads and concurrency / Safety
Presentation transcript:

Programming Design Patterns Last Week Interfaces can reduce the coupling between classes Composition vs Inheritance Favor Composition over inheritance Composition gives more flexibility in terms of being easier to change code. Lets you encapsulate a family of algorithms in their own classes (implementing interfaces) Programming Design Patterns 11/20/2018

Programming Design Patterns Java basics Default access of methods in an interface? Default access of methods in a class? Can Interfaces have instance fields? Can Interfaces have constants? Can Interfaces have “public static final” access for constants? Programming Design Patterns 11/20/2018

Programming Design Patterns Java Basics Methods in an interface are public by default Methods in a class have package access by default Interfaces cannot have instance fields but can have constants also, avoid declaring constants via interfaces use Enums instead (check slides in java guidelines section) public interface SharedBuffer { int CAPACITY = 100; } Fields in an interface are automatically “public static final”. So, no need to use those keywords. Access the constants using if (x < SharedBuffer.CAPACITY) … Programming Design Patterns 11/20/2018

Java basics: Types and Interfaces SharedBufferInterface x; What is the type of x? How many objects can x refer to in its lifetime? Programming Design Patterns 11/20/2018

Java basics: Types and Interfaces SharedBufferInterface x; The object to which x refers doesn't have the type SharedBufferInterface Instead, the type of the object is some class that implements the SharedBufferInterface interface Note that x can refer to objects of different types during its lifetime. x = new VectoredBuffer(); x = new ArrayListBuffer(); Programming Design Patterns 11/20/2018

Invocation based on momentary contents of an instance variable The Java virtual machine locates the correct method that belongs to the class of the actual object. Fruit x = new Fruit(); Apple x = new Apple(); x.peel() invocation on x can call different methods depending on the momentary contents of x. Homework Apple apple = new Fruit(); apple.peel() ?? Programming Design Patterns 11/20/2018

Programming Design Patterns Polymorphism The principle that the actual type of the object determines the method to be called is called polymorphism. The term “polymorphism” comes from the Greek words for “many shapes”. In Java, all instance methods are polymorphic. Polymorphism denotes the principle that behavior can vary depending on the actual type of an object. Programming Design Patterns 11/20/2018

Programming Design Patterns Method overloading the same method name can refer to different methods when a method name is overloaded: when a single class has several methods with the same name but different parameter types. Early binding and Late binding What does it mean for a language to be type safe? Homework Programming Design Patterns 11/20/2018

Overloading and polymorphism Polymorphism and Method Overloading which one is early-binding? Late-binding? There is an important difference between polymorphism and overloading. polymorphism: late binding only at run-time is the contents of the instance variable known overloading: early binding Programming Design Patterns 11/20/2018

Programming Design Patterns Early and late binding Early binding of methods occurs if the compiler selects a method from several possible candidates. Late binding occurs if the method selection takes place when the program runs. The compiler picks an overloaded method when translating the program, before the program ever runs This method selection is called early binding . However, when selecting the appropriate peel() method in a call x.peel(), the compiler does not make any decision when translating the method call. The program has to run before anyone can know what is stored in x. Therefore, the virtual machine, and not the compiler, selects the appropriate method. This method selection is called late binding . Programming Design Patterns 11/20/2018

Memory Management in Java What is the order of garbage collection? What is the role of the finalize() method? What resources can be freed using the finalize method()? Programming Design Patterns 11/20/2018

Programming Design Patterns Memory Management (2) the order of garbage collection is not guaranteed Do not depend on the order (of threads) running the finalize() code of each object. If you use finalize() to release non-memory resources, note that garbage collection is not guaranteed Add code to remove descriptors, if they are not already collected Use finalize() to release memory allocated for some C-calls (calls made through the native interface). Programming Design Patterns 11/20/2018

Programming Design Patterns Memory Management (3) finalize() method is in java.lang.Object So every class inherits it It does not perform any actions in java.lang.Object It is designed to be overridden to clean up non-Java resources (files, etc.) Should super.finalize() be called? always? Never? Makes no difference? What if an exception is thrown in finalize()? How many times is finalize() run per object? Super.finalize(): safety measure to not miss closing resources in the super class Exception in finalize() halts its execution Programming Design Patterns 11/20/2018

Programming Design Patterns Memory Management (4) finalize() method is in java.lang.Object So every class inherits it It does not perform any actions in java.lang.Object It is designed to be overridden to clean up non-Java resources (files, etc.) Should super.finalize() be called: Always What if an exception is thrown in finalize()? The exception is ignored for the object, and finalize() for that object is skipped. How many times is finalize() run per object? Once Super.finalize(): safety measure to not miss closing resources in the super class Exception in finalize() halts its execution Programming Design Patterns 11/20/2018

Programming Design Patterns Memory Management (5) protected void finalize() throws Throwable { try { …close(); // close the open files in this class } finally { super.finalize(); } Programming Design Patterns 11/20/2018

Large number of threads in an application If a program creates a huge number of threads does this affect the performance of the application? Why? What is the cost associated with each thread? Why is it important to be able to stop specific threads during their execution? Maybe multiple threads are trying to solve the same problem? So, terminate the rest. Or, there is an error that will affect all the threads later on (reading form a database, file, etc.) Programming Design Patterns 11/20/2018

Programming Design Patterns Pool of threads A program that creates a huge number of short-lived threads can be inefficient. Threads are managed by the operating system, and there is a space and run-time cost for each thread that is created. This cost can be reduced by using a thread pool. A thread pool creates a number of threads and keeps them alive. Runnable r1 = new GreetingRunnable("Hello, World!"); Runnable r2 = new GreetingRunnable("Goodbye, World!"); ThreadPool pool = ThreadPool.newFixedPool(MAX_THREADS); pool.execute(…); . Programming Design Patterns 11/20/2018

Programming Design Patterns Pool of threads (2) The cost of creating threads is minimized. Thread pools are particularly important for server programs database and web servers, that repeatedly execute requests from multiple clients. Rather than spawning a new thread for each request, the requests are implemented as runnable objects and submitted to a thread pool. However, the runnables that are run by a particular thread are executed sequentially, not in parallel. Programming Design Patterns 11/20/2018

Programming Design Patterns Terminating a thread A thread terminates when run method terminates. May need to explicitly stop a thread when a pool of threads is working on a problem one of the thread finishes, rest need to stop stop() method on the Thread class deprecated, has side effects. Examples? t.interrupt() sets a boolean flag thread should do the necessary cleanup If the thread has access to resources (like file descriptors, etc). Programming Design Patterns 11/20/2018

Thread: check if it is interrupted public void run() { for (int i = 1; i <= REPETITIONS && !Thread.interrupted(); i++) { Do work } Clean up } What if the thread is sleeping? If the thread has access to resources (like file descriptors, etc). Programming Design Patterns 11/20/2018

Interrupting a sleeping thread public void run() { try { for (int i = 1; i <= REPETITIONS; i++) { Do work, including call to sleep(…) } } catch (InterruptedException exception) { … MORE WORK AND CLEANUP If a thread is sleeping, it can't execute code that checks for interruption The sleep method is terminated with an InterruptedException whenever a sleeping thread is interrupted. The sleep method also throws an Interrupted-Exception when it is called in a thread that is already interrupted. Programming Design Patterns 11/20/2018

InterruptedException: summary When a thread is interrupted, the most common response is to terminate the run method. Putting a thread to sleep is potentially risky—a thread might sleep for so long that it is no longer useful and should be terminated. to terminate a thread, you interrupt it. When a sleeping thread is interrupted, an InterruptedException is generated. You need to catch that exception in your run method and terminate the thread. The simplest way to handle thread interruptions is to give your run method the following form (next slide) Programming Design Patterns 11/20/2018

Summary: Thread’s run() method public void run() { try { Task statements } catch (InterruptedException exception) { // … } Programming Design Patterns 11/20/2018

Programming Design Patterns Race conditions What is a race condition? When threads share access to a common object, they can conflict with each other. A race condition occurs if the effect of multiple threads on shared data depends on the order in which the threads are scheduled. Programming Design Patterns 11/20/2018

Programming Design Patterns Object Pool One of the “Creational Patterns” Useful when cost of initializing an instance is high rate of instantiation of a class is high the number of instantiations in use is low at any time Features Provide object caching Restricts number of objects created Clients can ask the pool for an instance Should have only one instance of the ObjectPool class So that they can be managed with a uniform policy Provide a way to clean up unused objects periodically Homework/Classwork Design API for an ObjectPool class Each object (pre 1.5) had only one condition variable Programming Design Patterns 11/20/2018

Programming Design Patterns Object Pool An object pool is useful to manage the creation of objects, keeping track of how many are active, how many are idle, allowing creation of specific classes of objects, returning objects to the pool, invalidating some objects, etc. What methods should an Object pool have? Declare the Singleton class or the getInstance() method to be final Programming Design Patterns 11/20/2018

Programming Design Patterns Object Pool Create ObjectPool class with private array of Objects inside Create acquire and release methods in ObjectPool class Make sure that the ObjectPool class has only ONE instance in the entire application Programming Design Patterns 11/20/2018

Object Pool: some methods addObject(…) borrowObject(…) returnObject(Object obj); setFactory(PoolableObjectFactory factory); clear(); close(); getNumActive(); getNumIdle(); invalidateObject(Object obj); Declare the Singleton class or the getInstance() method to be final Programming Design Patterns 11/20/2018

Object Pool: using an object from the pool Object obj = null; try { obj = pool.borrowObj(); // code to use the object } catch (Exception e) { // invalidate the object, but don’t return to the pool // catch a more specific exception // can move the invalidation to the finally clause pool.invalidateObject(obj); obj = null; } finally { // if the object is not null, return it to the pool if (null != obj) { pool.returnObject(obj); } Declare the Singleton class or the getInstance() method to be final Invalidate: suppose each thread is given a different port number and a particular port number is giving an error (because it is occupied), then invalidate it. Programming Design Patterns 11/20/2018

Programming Design Patterns Singleton Patterns One instance of a class or one value accessible globally in an application. Ensures a unique instance We find this pattern most useful when we need to share the same object from many parts of the program We have to ensure that it is exactly the same object because it holds some data that everyone shares Difference between a singleton class and a static class? Static class is one way to make a class “Singleton”. Programming Design Patterns 11/20/2018

Programming Design Patterns Singleton Patterns Example usage Reference count Thread pools Caches Registry settings Object that handles preferences Object for logging Object for device driver to printer/graphics-card Programming Design Patterns 11/20/2018

Programming Design Patterns Singleton Pattern (2) Single pattern is a convention. Provides a global point of access Just like a global variable (without the downside) If you assign an object to a global variable, it is created when the application starts even if the object is never used Singleton pattern creates objects ONLY if needed ClassWork Write a Java class with a static method, getInstance(), that returns an instance of that class, if it has not been created It should not be possible to call the constructor of this class from outside the class Programming Design Patterns 11/20/2018

Singleton Pattern Example (1) public class Singleton { private static Singleton uniqueInstance; // private constructor private Singleton() {} public static Singleton getInstance() { if (uniqueInstance == null) { uniqueInstance = new Singleton(); } return uniqueInstance; // Other methods Programming Design Patterns 11/20/2018

Singleton Pattern Example (2) Fix previous example so that it works with multiple threads public static synchronized Singleton getInstance() { if (uniqueInstance == null) { uniqueInstance = new Singleton(); } return uniqueInstance; Programming Design Patterns 11/20/2018

Singleton Pattern Example (3) Should every thread be required to wait for its turn before entering the method? Synchronization is expensive Synchronization of a method can significantly decrease the performance worse if the getInstance is called multiple times but synchronization is needed only to create the instance Once the instance is created, no more synchronization is needed Class Work Write code to create the unique instance when the class is loaded Synchronization of a method can decrease the performance by a factor of 100! Programming Design Patterns 11/20/2018

Singleton Pattern Example (4) Create the unique instance when the class is loaded before any thread can access uniqueInstance variable but created if it is not used public class Singleton { private static Singleton uniqueInstance = new Singleton(); private Singleton() {}; public static Singleton getInstance() { return uniqueInstance; } Programming Design Patterns 11/20/2018

Singleton Pattern Example (5) Use “double-checked locking” Chapter 5: page 182 Homework What if a sub-class of the Singleton class is created? Will that violate properties of the Singleton pattern? Declare the Singleton class or the getInstance() method to be final Programming Design Patterns 11/20/2018