Presentation is loading. Please wait.

Presentation is loading. Please wait.

Programming Design Patterns

Similar presentations


Presentation on theme: "Programming Design Patterns"— Presentation transcript:

1 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

2 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

3 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

4 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

5 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

6 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

7 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

8 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

9 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

10 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

11 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

12 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

13 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

14 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

15 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

16 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

17 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

18 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

19 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

20 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

21 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

22 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

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

24 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

25 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

26 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

27 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

28 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

29 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

30 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

31 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

32 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

33 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

34 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

35 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

36 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

37 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


Download ppt "Programming Design Patterns"

Similar presentations


Ads by Google