Threads and Singleton. Threads  The JVM allows multiple “threads of execution”  Essentially separate programs running concurrently in one memory space.

Slides:



Advertisements
Similar presentations
Chapter 5: The Singleton Pattern
Advertisements

Operating Systems: Monitors 1 Monitors (C.A.R. Hoare) higher level construct than semaphores a package of grouped procedures, variables and data i.e. object.
50.003: Elements of Software Construction Week 6 Thread Safety and Synchronization.
Practice Session 7 Synchronization Liveness Deadlock Starvation Livelock Guarded Methods Model Thread Timing Busy Wait Sleep and Check Wait and Notify.
Concurrency 101 Shared state. Part 1: General Concepts 2.
Jan Ron McFadyen1 Singleton To guarantee that there is at most one instance of a class we can apply the singleton pattern. Singleton Static.
Oct Ron McFadyen1 Singleton To guarantee that there is at most one instance of a class we can apply the singleton pattern. Singleton Static.
Concurrency and Thread Yoshi. Two Ways to Create Thread Extending class Thread – Actually, we need to override the run method in class Thread Implementing.
Threads Load new page Page is loading Browser still responds to user (can read pages in other tabs)
Road Map Introduction to object oriented programming. Classes
Implications of Substitution Fall 2005 OOPD John Anthony.
Evan Korth New York University Computer Science I Classes and Objects Professor: Evan Korth New York University.
Synchronization in Java Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
Spring 2010ACS-3913 Ron McFadyen1 Singleton To guarantee that there is at most one instance of a class we can apply the singleton pattern. Singleton Static.
Fall 2009ACS-3913 R McFadyen1 Singleton Problem: Exactly one instance of a certain object is required (this object is called a singleton). We must ensure.
1 What is the “volatile” Keyword? You can skip locking (thread synchronization) in some cases by using the volatile variables. –No locking/unlocking =
Terms and Rules Professor Evan Korth New York University (All rights reserved)
1 Sharing Objects – Ch. 3 Visibility What is the source of the issue? Volatile Dekker’s algorithm Publication and Escape Thread Confinement Immutability.
Definitions Process – An executing program
1 MATERI PENDUKUNG SINKRONISASI Matakuliah: M0074/PROGRAMMING II Tahun: 2005 Versi: 1/0.
1 Further OO Concepts II – Java Program at run-time Overview l Steps in Executing a Java Program. l Loading l Linking l Initialization l Creation of Objects.
Winter 2007ACS-3913 Ron McFadyen1 Singleton To guarantee that there is at most one instance of a class we can apply the singleton pattern. Singleton Static.
Programming Languages and Paradigms Object-Oriented Programming.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
!!! Global Variables!!! are EVIL SSimply because you just write a school boy/gal?
Threading and Concurrency Issues ● Creating Threads ● In Java ● Subclassing Thread ● Implementing Runnable ● Synchronization ● Immutable ● Synchronized.
Lecture 5 : JAVA Thread Programming Courtesy : MIT Prof. Amarasinghe and Dr. Rabbah’s course note.
1 Concurrent Languages – Part 1 COMP 640 Programming Languages.
111 © 2002, Cisco Systems, Inc. All rights reserved.
Computer Science 313 – Advanced Programming Topics.
ABSTRACT The real world is concurrent. Several things may happen at the same time. Computer systems must increasingly contend with concurrent applications.
Internet Software Development Controlling Threads Paul J Krause.
Singleton and Basic UML CS340100, NTHU Yoshi. What is UML Unified Modeling Language A standardized general-purpose modeling language in the field of software.
Synchronized and Monitors. synchronized is a Java keyword to denote a block of code which must be executed atomically (uninterrupted). It can be applied.
Threads Opening Discussion zWhat did we talk about last class? zDo you have any questions about the assignment?
Java Thread and Memory Model
Threading and Concurrency COM379T John Murray –
15.1 Threads and Multi- threading Understanding threads and multi-threading In general, modern computers perform one task at a time It is often.
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.
Singleton Duchenchuk Volodymyr Oksana Protsyk. 2 /48.
1 Chapter 5: Defining Classes. 2 Basics of Classes An object is a member of a class type What is a class? Fields & Methods Types of variables: –Instance:
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Concurrency & Dynamic Programming.
CS533 – Spring Jeanie M. Schwenk Experiences and Processes and Monitors with Mesa What is Mesa? “Mesa is a strongly typed, block structured programming.
Threads in Java Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without.
Singleton Pattern Presented By:- Navaneet Kumar ise
The Singleton Pattern (Creational)
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Singleton Pattern. Problem Want to ensure a single instance of a class, shared by all uses throughout a program Context Need to address initialization.
Week 9, Class 3: Java’s Happens-Before Memory Model (Slides used and skipped in class) SE-2811 Slide design: Dr. Mark L. Hornick Content: Dr. Hornick Errors:
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.
Java Thread Programming
Concurrency 2 CS 2110 – Spring 2016.
Multithreading / Concurrency
Design Patterns – Chocolate Factory (from Head First Design Patterns)
The Singleton Pattern SE-2811 Dr. Mark L. Hornick.
Lecture 25 More Synchronized Data and Producer/Consumer Relationship
Threads, Concurrency, and Parallelism
Definitions Concurrent program – Program that executes multiple instructions at the same time. Process – An executing program (the running JVM for Java.
Programming Design Patterns
Multithreading.
Singleton Pattern Pattern Name: Singleton Pattern Context
Singleton design pattern
CS 350 – Software Design Singleton – Chapter 21
Session 2: Introduction to Object Oriented Programming
Threads and Multithreading
CSE 542: Operating Systems
More concurrency issues
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Threads and concurrency / Safety
Presentation transcript:

Threads and Singleton

Threads  The JVM allows multiple “threads of execution”  Essentially separate programs running concurrently in one memory space  No inherent guarantees about the order in which different threads execute  Threads take turns executing and one may be stopped to let another run at any time  The JVM allows multiple “threads of execution”  Essentially separate programs running concurrently in one memory space  No inherent guarantees about the order in which different threads execute  Threads take turns executing and one may be stopped to let another run at any time

Dining Philosophers  Five philosophers around a table with five forks spread between them  All philosophers do is think and eat  To eat, a philosopher must hold both of the forks next to it.  Can you cause deadlock?  Which rules for the philosophers cause deadlocks and which ones prevent it?  Five philosophers around a table with five forks spread between them  All philosophers do is think and eat  To eat, a philosopher must hold both of the forks next to it.  Can you cause deadlock?  Which rules for the philosophers cause deadlocks and which ones prevent it?

Look at Code  Each philosopher is a separate thread  The state of the forks is shared (static)  Will it run to completion?  Each philosopher is a separate thread  The state of the forks is shared (static)  Will it run to completion?

Preventing deadlock  Pick up lower numbered fork  Pick up higher numbered fork  Eat  Put down higher numbered fork  Put down lower numbered fork  Think  Forever  Pick up lower numbered fork  Pick up higher numbered fork  Eat  Put down higher numbered fork  Put down lower numbered fork  Think  Forever

Singleton  Used when you only want one instance of a class  Make constructor private and, instead, give everyone a reference to the same instance  Used when you only want one instance of a class  Make constructor private and, instead, give everyone a reference to the same instance

Example  Check out the code in Singleton

public class Professor { private boolean isTeaching; // other variables private static Professor uniqueProfessor; private Professor() { isTeaching = false; //other assignments } public static Professor getProfessor() { if (uniqueProfessor == null) { uniqueProfessor = new Professor(); return uniqueProfessor; } return uniqueProfessor; } //other methods }

Singleton Pattern Definition  The Singleton Pattern ensures a class has only one instance, and provides a global point of access to that instance.

Singleton Pattern UML Singleton static uniqueInstance private Singleton() static getInstance()

Why Did I Show You Threads?  What happens if we have multiple threads getting singletons?  Is there a place a thread could be interrupted that would cause problems?  What happens if we have multiple threads getting singletons?  Is there a place a thread could be interrupted that would cause problems?

Synchronized  Adding the keyword “synchronized” to the definition of a method means that only one thread can be executing that method at any point in time  Adding Synchonized to the getProfessor would certainly fix our problem  Has a non-trivial performance penalty  Adding the keyword “synchronized” to the definition of a method means that only one thread can be executing that method at any point in time  Adding Synchonized to the getProfessor would certainly fix our problem  Has a non-trivial performance penalty

public class SyncProfessor { private boolean isTeaching; // other variables private static SyncProfessor uniqueProfessor; private SyncProfessor() { isTeaching = false; //other assignments } private static synchronized SyncProfessor getProfessor() { if (uniqueProfessor == null) { uniqueProfessor = new SyncProfessor(); } return uniqueProfessor; } //other methods }

Eager Creation vs. Lazy Creation  Eager: initialize at variable declaration (created when the class is loaded)  WATCH OUT! If construction depends on information not available at load time (constructor parameters), can’t use eager construction.  Eager: initialize at variable declaration (created when the class is loaded)  WATCH OUT! If construction depends on information not available at load time (constructor parameters), can’t use eager construction.

Double Checked Locking  Look at DoubleCheckedProfessor  “Volatile” marks a member variable not to be used in optimization, during compilation  “synchronized” obtains and releases locks on monitors  “volatile” only available with Java 1.5 and later!  Look at DoubleCheckedProfessor  “Volatile” marks a member variable not to be used in optimization, during compilation  “synchronized” obtains and releases locks on monitors  “volatile” only available with Java 1.5 and later!

public class DoubleCheckedProfessor { private boolean isTeaching; private volatile static DoubleCheckedProfessor uniqueProfessor; private DoubleCheckedProfessor() { isTeaching = false; } private static DoubleCheckedProfessor getProfessor() { if (uniqueProfessor == null) { synchronized (DoubleCheckedProfessor.class) { if (uniqueProfessor == null) { uniqueProfessor = new DoubleCheckedProfessor(); } return uniqueProfessor; } //other methods }