1 Chapter 8 Three Interfaces: Cloneable, Serializable, and Runnable.

Slides:



Advertisements
Similar presentations
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.
Advertisements

Spring/2002 Distributed Software Engineering C:\unocourses\4350\slides\DefiningThreads 1 Serialization Flatten your object for automated storage or network.
Multi-threaded applications SE SE-2811 Dr. Mark L. Hornick 2 What SE1011 students are told… When the main() method is called, the instructions.
1 CSC321 §2 Concurrent Programming Abstraction & Java Threads Section 2 Concurrent Programming Abstraction & Java Threads.
Java How to Program, 9/e CET 3640 Professor: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
1 L49 Multithreading (1). 2 OBJECTIVES  What threads are and why they are useful.  How threads enable you to manage concurrent activities.  The life.
CS220 Software Development Lecture: Multi-threading A. O’Riordan, 2009.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
Definitions Process – An executing program
Java How to Program, 9/e CET 3640 Professor: Dr. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Parallel Processing (CS526) Spring 2012(Week 8).  Thread Status.  Synchronization in Shared Memory Programming(Java threads ) ◦ Locks ◦ Barriars.
Java Programming: Advanced Topics
1 Java Threads and Synchronization Review Modified from slides taken from
Java Programming, Second Edition Chapter Seventeen Multithreading and Animation.
1 Java Threads Instructor: Mainak Chaudhuri
Threads. Java Threads A thread is not an object A thread is a flow of control A thread is a series of executed statements A thread is a nested sequence.
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.
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.
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.
Multithreading : synchronization. Avanced Programming 2004, Based on LYS Stefanus’s slides slide 4.2 Solving the Race Condition Problem A thread must.
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.
Threads in Java. Processes and Threads Processes –A process has a self-contained execution environment. –Has complete set of runtime resources including.
CSE 501N Fall ‘09 23: Advanced Multithreading: Synchronization and Thread-Safety December 1, 2009 Nick Leidenfrost.
Object Persistence and Object serialization CSNB534 Asma Shakil.
Operating Systems ECE344 Ashvin Goel ECE University of Toronto Mutual Exclusion.
CSC321 Concurrent Programming: §5 Monitors 1 Section 5 Monitors.
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.
Multithreading Chapter Introduction Consider ability of human body to ___________ –Breathing, heartbeat, chew gum, walk … In many situations we.
In Java processes are called threads. Additional threads are associated with objects. An application is associated with an initial thread via a static.
Multithreading in JAVA
Object-oriented Programming in Java. © Aptech Ltd. Introduction to Threads/Session 7 2  Introduction to Threads  Creating Threads  Thread States 
Java Thread and Memory Model
Threads Doing Several Things at Once. Threads n What are Threads? n Two Ways to Obtain a New Thread n The Lifecycle of a Thread n Four Kinds of Thread.
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.
Concurrency Control 1 Fall 2014 CS7020: Game Design and Development.
©SoftMoore ConsultingSlide 1 Serialization. ©SoftMoore ConsultingSlide 2 Serialization Allows objects to be written to a stream Can be used for persistence.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Threads. Objectives You must be able to answer the following questions –What code does a thread execute? –What states can a thread be in? –How does a.
A running program is a collection of “threads” – essentially independent execution streams When the main() method is called, the instructions within.
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. Multitasking The multitasking is the ability of single processor to perform more than one operation at the same time Once systems allowed.
CSC CSC 143 Threads. CSC Introducing Threads  A thread is a flow of control within a program  A piece of code that runs on its own. The.
1 Threads in Java Jingdi Wang. 2 Introduction A thread is a single sequence of execution within a program Multithreading involves multiple threads of.
Software Design 13.1 From controller to threads l Threads are lightweight processes (what’s a process?)  Threads are part of a single program, share state.
1 CSE 331 Memento Pattern and Serialization slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
Mutual Exclusion -- Addendum. Mutual Exclusion in Critical Sections.
Concurrent Programming in Java Based on Notes by J. Johns (based on Java in a Nutshell, Learning Java) Also Java Tutorial, Concurrent Programming in Java.
Threads in Java Jaanus Pöial, PhD Tallinn, Estonia.
Multithreading / Concurrency
Multi Threading.
Multithreaded Programming in Java
Threads Chate Patanothai.
Definitions Concurrent program – Program that executes multiple instructions at the same time. Process – An executing program (the running JVM for Java.
Multithreading Chapter 23.
Multithreading.
Serialization and Deserialization Bullet points from Head First Java, Ch Dec-18 serialization.ppt.
Multithreading.
Multithreaded Programming
Concurrency in Java Last Updated: Fall 2010 Paul Ammann SWE 619.
CSE 331 Memento Pattern slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
Multithreading in java.
Threads and Multithreading
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

1 Chapter 8 Three Interfaces: Cloneable, Serializable, and Runnable

2 Cloning objects To clone an object is to make an exact copy of it. A cloned object should be independent of the source object from which it is cloned. An object is cloned by invoking its method clone(), which has protected scope in Object.

3 Cloning basics To enable cloning, a class declares the clone() method inherited ultimately from Object as public. In Object, the method is protected. A public override of the inherited clone() method should throw a CloneNoteSupportedException.

4 Cloning basics If a class’s fields include object or array references, the clone() override must ensure that, after the cloning, the source and target objects are independent. Object ’s method clone() simply copies references so that a clone source and target wind up with references to the same object.

5 Cloning basics Arrays can be cloned. A cloned array has the same number of elements and the same contents as the source array. Cloning can be disabled by having a public override of clone() explicitly throw a CloneNotSupportedException.

6 Serialization basics Serialization is the process of transforming an in-memory object to a byte stream. Deserialization is the inverse process of reconstructing an object from a byte stream to the same state in which the object was previously serialized. “Serializing out” and “serializing in” are also used.

7 Serialization basics The requirements for serialization are straightforward: –Only class instances rather than primitive types can be serialized. –For an object to be serializable, its class or some ancestor must implement the empty Serializable interface. –An empty interface is called a marker interface.

8 Serialization basics The syntax for serialization is straightforward: –An object is serialized by writing it to an ObjectOutputStream. –An object is deserialized by reading it from an ObjectInputStream.

9 Serialization code FileOutputStream out = new FileOutputStream( “save.ser” ); ObjectOutputStream oos = new ObjectOutputStream( out ); oos.writeObject( new Date() ); oos.close();

10 Deserialization code FileInputStream in = new FileInputStream( “save.ser” ); ObjectInputStream ois = new ObjectInputStream( in ); Date d = (Date) ois.readObject(); ois.close();

11 Object graphs If an object has references to other objects or arrays, the entire object graph is serialized when the object is serialized. –The object graph consists of the object directly serialized and any other objects or arrays to which the object has direct or indirect references.

12 Nonserializable superclasses If a serializable class C has a nonserializable superclass S, instances of C still can be serialized if S has an accessible no- argument constructor. –S ’s no-argument constructor is invoked automatically during deserialization to construct the “ S -part” of the deserialized object.

13 Serialization and primitive types Technically, primitive types cannot be serialized or deserialized. However, the ObjectOutputStream implements the DataOutput interface, which declares methods such as writeInt to write primitive types to streams. ObjectInputStream implements DataInput for reading primitive types.

14 transient and static fields A field marked as transient is not impacted by serialization. –During deserialization, transient fields are restored to their default values (e.g., transient numeric fields are restored to zero). static fields are not impacted by serialization.

15 Customization Serialization and deserialization can be customized by providing private callback methods named writeObject and readObject, respectively. The Externalizable interface can be implemented by classes that need to have complete control over serialization and deserialization.

16 Cautionary notes The same object should not be repeatedly serialized to the same stream. A class should not be redefined in between the serialization and deserialization of its instances. Classes that need to disable serialization can throw a NotSerializableException in the private callback writeObject.

17 Multithreading basics A thread of control is a sequence of instructions that execute in the JVM. Java programs begin as single-threaded programs but can become multithreaded by constructing and starting Thread s. A program can have arbitrarily many threads of execution.

18 Multithreading basics A typical code segment to construct and start a thread is Thread t = new Thread( this ); t.start(); where this refers to a Runnable target. A runnable target is an object whose class implements the Runnable interface.

19 Multithreading basics The Runnable interface declares a single method public void run(); The run() method is a pure callback; that is, the programmer defines but never invokes run(). The system invokes run() to execute a thread; the programmer invokes start().

20 Multithreading basics If Thread is extended, the subclass should override the inherited run(), which returns immediately. –The override of run() provides whatever code a thread should execute. –A thread stops permanently once it returns from run(). –A stopped thread cannot be restarted.

21 Thread priorities If a program has multiple threads of the same priority executing, then thread execution is interleaved in unpredictable ways. Threads have priorities ranging from MIN_PRIORITY through MAX_PRIORITY, which are numeric constants.

22 Thread priorities Although the range for thread priorities is not standardized, typical values are –1 for MIN_PRIORITY. –5 for NORM_PRIORITY. –10 for MAX_PRIORITY. The JVM uses priority-based, preemptive scheduling: a higher priority thread always preempts a lower priority thread.

23 Thread priorities If two threads T1 and T2 are started, but T2 has a higher priority than T1, then T2 preempts T1 if T1 is executing; and T1 does not execute again until T2 stops. A thread of a given priority P starts another thread of the same priority. The setPriority can change a thread’s priority before the thread is started.

24 User and daemon threads Threads are of two types: user threads and daemon threads. A program continues to run so long as at least one user thread is alive. By contrast, a daemon thread by itself cannot sustain a program’s execution. The garbage collector runs as a daemon thread.

25 User and daemon threads A user thread constructs a user thread; a daemon thread constructs a daemon thread. The setDaemon method can be invoked to change a thread’s daemon status before the thread is started. Daemon threads are “helper” threads for user threads.

26 Thread states A thread is one of four possible states: –Initial state. A newly constructed thread is in its initial state until started. –Runnable state. Once started, a thread is runnable or “alive” until the thread stops. –Blocked state. A thread can be blocked in various ways, e.g., by sleeping or waiting. A blocked thread becomes runnable once unblocked.

27 Thread states –Stop state. A thread enters the stop state if it returns from run() or the deprecated stop() method is invoked on it. Once stopped, a thread cannot be restarted. If a thread needs to run indefinitely, the run() method can have an infinite loop in it.

28 Thread groups Every thread belongs to a ThreadGroup, which is either explicitly named or a default thread group. Thread groups are a convenience. For instance, if several threads belong to a group, then setDaemon could be invoked on the group as a whole instead of on each individual thread.

29 Thread synchronization Suppose that threads T1 and T2 read and write a shared field. In this case, T1 and T2 need to be synchronized so that, for example, T1 is not reading while T2 is writing. (Write operations are not “atomic” but rather consist of (a) evaluating the assignment value and (b) assigning the value to the target.)

30 Thread synchronization Java provides a lock construct to ensure single-threaded execution of critical section code, that is, code to which threads must have mutually exclusive access. The synchronized keyword can be used to lock a block of code within a method or an entire method.

31 Thread synchronization The code segment synchronized( this ) { // single-threaded execution } shows the syntax of a synchronized block. The lock is the object to which this refers. A synchronized block requires an object as a lock.

32 Thread synchronization The code segment synchronized void getChopsticks() { //... single-threaded execution } shows the syntax for a synchronized method. The implicit lock is the object to which this refers.

33 Thread synchronization A thread that gains a lock can invoke wait to release the lock until a subsequent invocation of notify or notifyAll by the thread that gains the lock. –Invocation of wait is guaranteed to be “atomic” or “noninterruptable.” –A thread that invokes wait simultaneously releases the lock and goes into a waiting state.

34 Thread synchronization notify awakens an arbitrary waiting thread, whereas notifyAll awakens all waiting threads. –Either method can be invoked even if no threads happen to be waiting at the time. –The methods awaken only threads that went into a wait state beforehand. –The methods are typically invoked as the last statement in a synchronized block or method.

35 Deadlock Synchronization locks open the possibility of deadlock, a condition that involves at least two threads. In deadlock, each thread holds a lock and releases it only when the other threads release their locks. The JVM does not detect, prevent, or recover from deadlock. The programmer must avoid deadlock.

36 The join method Suppose that t1 and t2 refer to two threads and that the t1 -thread invokes t2.join(); // wait for t2 to stop The invocation causes the t1 -thread to wait until the t2 -thread stops. The join method is a powerful construct for thread synchronization.

37 Deprecated thread methods The stop method has been deprecated. The preferred way to stop a thread is to have the thread return from run(). –A stopped thread releases any held locks. The suspend and resume methods have been deprecated because suspend is deadlock-prone and resume is used only in conjunction with suspend.

38 Critical section problems Solutions to critical section problems are judged on four criteria. The synchronization mechanism in Java helps satisfy two of the four criteria.

39 Critical section problems The four criteria are: –Progress. If a critical section is unlocked, a thread should be able to enter it. The synchronized construct ensures this behavior. –Mutual exclusion. At most one thread can hold a lock only a critical section. The synchronized construct ensures this behavior.

40 Critical section problems –Starvation. None of the threads trying to enter a critical section should be permanently prevented from doing so. The synchronized construct does not prevent starvation. –Fairness. Each of N contending threads should enter the critical section roughly the same amount of time. The synchronized construct does not ensure fairness.