Outline. Command Pattern. Examples. Goal & Applications Motivation (undo / redo) Structure & participants Sequence diagram

Size: px
Start display at page:

Download "Outline. Command Pattern. Examples. Goal & Applications Motivation (undo / redo) Structure & participants Sequence diagram"

Transcription

1 Outline Command Pattern Goal & Applications Motivation (undo / redo) Structure & participants Sequence diagram Examples javax.swing.action java.util.timer java.util.concurrent.executorservice Callable & Future: asynchronous programming 11 May

2 Command Pattern Goal Turn an action into an object (command), i.e. encapsulate all the information needed to call an action at a later time Client instantiates the command and provides the information needed to call the method at a later time (receiver, method name, parameters) Command may be stored and may be executed at a later time Invoker does not need to know the receiver of the method nor the method parameters (they are stored in the command object) Decouple the class that is invoking the action from the action itself 11 May

3 Command Pattern Applications Transactional behavior Similar to the undo, a database engine keeps a list of operations that have been (or will be) performed. If one of them fails, a rollback is executed Wizards Command object is created when the wizard is first displayed Each wizard page stores its GUI changes in the command object "Finish" executes the command Actions in Swing: an Action is a command object Thread Pool: actions are registered to be executed Macro recording: user interactions can be recorded Multi-level undo User actions are stored in an undo history stack 11 May

4 Undo / Redo Motivation op 1 op 2 op 3 op 4 op 5 current position Remarks: Association of undo/redo list with model or with view? What happens if a new operation is executed at the current position? 11 May

5 Undo / Redo Emacs / vim support undo-trees 11 May

6 Undo / Redo Implementation S 0 S 1 S 2 S 3 Copy and save the states Figure list has to be (deep) cloned upon every operation Copy and save the changes The changes have to be represented as command objects 11 May

7 Undo / Redo DrawCommand redo() undo() AddCommand redo() undo() Model m Figure f m.addfigure(f) m.removefigure(f) MoveCommand redo() undo() Figure f int dx, dy f.move(dx, dy) f.move(-dx, -dy) GroupCommand redo() undo() Figure g Model m for (Figure f:g.figs) m.removefigure(f); m.addfigure(g); 11 May

8 Undo / Redo State diagram for commands From the view of a single command 11 May

9 Undo / Redo: DrawCommandHandler public interface DrawCommandHandler { void addcommand(drawcommand cmd); void undo(); void redo(); // clears redo list // adds cmd to undo commands boolean undopossible(); boolean redopossible(); void clearhistory(); Implementation: List of commands (ListIterator supports methods next and previous) Two stacks 11 May

10 Command Pattern Definition Encapsulate a request as an object Allows to parameterize clients with different requests Client {creates ConcrCmd and sets receiver Example: ActionListener implementation 11 May

11 Command Pattern Participants Command Declares interface for executing commands Concrete Command Client Implements execute by invoking an operation on the receiver Creates a concrete command and sets the information needed to call the method at a later time (receiver and parameters) Invoker Decides when the method is called, i.e. Asks the command to carry out the request Receiver Knows how to execute the operation, i.e. Receiver executes the actual work to be done 11 May

12 Command Pattern Sequence Diagram 11 May

13 Undo / Redo: DrawCommandHandler Problem: Movement of a figure leads to many operations move(dx, dy) typically moves the figure only about 1-2 pixels Guarantees visual feedback All MoveCommand objects are stored in the undo-list Undo of such a move operation requires many undo invocations Solution: 11 May

14 Command Pattern Forces You have to provide a undo / redo management You have to queue commands Remember Observer Causality Problem You need to maintain a persistent log of commands executed You need to provide transaction support You have to support timed operations 11 May

15 Outline Command Pattern Goal & Applications Motivation (undo / redo) Structure & participants Sequence diagram Examples Functional Interfaces, Lambda Expressions and Method references javax.swing.action java.util.timer java.util.concurrent.executorservice Callable & Future: asynchronous programming 11 May

16 Lambda Expression Argument List A list of parameters enclosed in parentheses Parameter types can be explicitly declared, or they can be inferred from the context. Empty parentheses indicate that there are no parameters. Parentheses can be omitted for a single parameter whose type can be inferred. Arrow Token "->", the lambda operator Body A function body, which can be either of the following: a statement block enclosed in braces a single expression (return type is that of the expression) 11 May

17 Lambda Expression: Examples (int x, int y) -> { return x + y; returns the sum of two integers (x, y) -> x + y Returns the sum of two numbers Types of the parameters and the return type are inferred from the context Body is a single expression; braces omitted n -> n % 2 == 0 Returns true if n is even (type is inferred) () -> 42 constant function, no parameters 11 May

18 Functional Interfaces & Lambda Expressions Functional Interface A functional interface is an interface with a single abstract method Default methods in interfaces are not abstract and do not count a functional interface may have multiple default Functional interfaces are recommended to have this annotation. This allows compilers to generate an error if the annotated interface does not satisfy the conditions. Lambda Expressions Conversion to a functional interface is the only thing you can do with a lambda expression in Java Pass it to a method parameter of a functional interface type Assign it to a variable of a functional interface type 11 May

19 Examples public interface Comparator<T> { int compare(t o1, T o2); java.awt.event.actionlistener public interface ActionListener extends EventListener { public void actionperformed(actionevent e); public interface Runnable { public abstract void run(); 11 May

20 Examples java.util.function.* public interface Function<T, R> { R apply(t t); public interface BiFunction<T, U, R> { R apply(t t, U u); public interface UnaryOperator<T> extends Function<T, T> { public interface BinaryOperator<T> extends BiFunction<T,T,T> { public interface Consumer<T> { void accept(t t); public interface BiConsumer<T, U> { void accept(t t, U u); public interface Supplier<T> { T get(); public interface Predicate<T> { boolean test(t t); public interface BiPredicate<T, U> { boolean test(t t, U u); 11 May

21 Types of Method References Reference to a static method Class::staticMethod (args) -> Class.staticMethod(args) String::valueOf String::format Reference to an instance method of a particular object instance::instancemethod (args) -> obj.instancemethod(args) s::tostring s::contains Reference to an instance method of an obj of a particular type Class:instanceMethod (obj, args) -> obj.instancemethod(args) String::toString String::contains s -> String.valueOf(s) (s,e1, ) -> String.format(s,e1, ) () -> s.tostring() (pat) -> s.contains(pat) s -> s.tostring() (s,pat) -> s.contains(pat) 11 May

22 Command Pattern Example: javax.swing.action Action Interface Useful extension to Action- Listener in cases where the same functionality may be accessed by several controls Supports: Text strings Icons NAME SHORT_DESCRIPTION LONG_DESCRIPTION SMALL_ICON Enabled/disabled state 11 May

23 Command Pattern Example: javax.swing.action public interface Action extends ActionListener { public static final String DEFAULT = "Default"; // not used public static final String NAME = "Name"; // menu or button public static final String SHORT_DESCRIPTION = "ShortDescription"; public static final String LONG_DESCRIPTION = "LongDescription"; public static final String SMALL_ICON = "SmallIcon"; public static final String ACTION_COMMAND_KEY= "ActionCommandKey"; public static final String ACCELERATOR_KEY = "AcceleratorKey"; public static final String MNEMONIC_KEY = "MnemonicKey"; public Object getvalue(string key); public void putvalue(string key, Object value); public void setenabled(boolean b); public boolean isenabled(); public void addpropertychangelistener(propertychangelistener l); public void removepropertychangelistener( PropertyChangeListener l); 11 May

24 Command Pattern Example: javax.swing.action Container Support Certain containers (menus, tool bars) know how to add an Action object => Upon adding an Action object: Container creates an appropriate component Container uses the Action properties to customize the component Renders component in enabled/disabled state Registers a listener on state changes Action may also be used to define (or be set on) a AbstractButton setaction JButton JButton(Action) JMenuItem JMenuItem(Action) JToggleButton JToggleButton(Action) [Radio/CheckBox] JTextField setaction JComboBox setaction 11 May

25 Timer (java.util.timer) Timer Facility to schedule tasks for future execution Tasks may be scheduled for one-time execution for repeated execution at regular intervals Fixed delay Fixed rate Each Timer instance uses a single background thread to execute the tasks Tasks should complete quickly, otherwise they hog the execution thread Timer does not offer real-time guarantees Implemented using a heap Task scheduling: O(log n) 11 May

26 Timer (java.util.timer) public class Timer { void cancel() // terminates this timer int purge() // Removes all cancelled tasks void schedule(timertask task, Date time) void schedule(timertask task, Date time, long period) void schedule(timertask task, long delay) void schedule(timertask task, long delay, long period) void scheduleatfixedrate(timertask t, Date time, long period) void scheduleatfixedrate(timertask t, long delay, long period) public abstract class TimerTask implements Runnable { abstract void run() // Action to be performed by this timer task boolean cancel() // Cancels this timer task long scheduledexecutiontime() // returns next execution time 11 May

27 Executor Framework Participants Worker: One thread is used to execute many unrelated tasks These threads are called worker threads / background threads May be organized in a thread pool (if more than one thread is used) May provide a flexible thread management Channel: A buffer which holds pending requests May be bounded 11 May

28 Executor Framework Executor = Channel + Workers public interface Executor { void execute(runnable command); Decouples task submission from task execution Executes the given command at some time in the future The command may be executed in a new thread / in a pooled thread / in the calling thread Task = Runnable public interface Runnable { void run(); Limitation: Method run cannot return a result (results are placed in shared fields) Method run cannot declare a checked exception 11 May

29 Executor: Simple Implementations DirectExecutor: Synchronous execution (in calling thread) class DirectExecutor implements Executor { public void execute(runnable r) { r.run(); Thread per task executor class ThreadPerTaskExecutor implements Executor { public void execute(runnable r) { new Thread(r).start(); 11 May

30 Executor: Advanced Implementations Execution Policies Execution order of submitted tasks (FIFO, LIFO, Priority Queue) Number of threads which execute concurrently Maximal size of queue with pending tasks Actions taken before / after task execution (startup/cleanup) Factory: java.util.concurrent.executors Provides several implementations for thread pools which implement different policies All factory methods return an executor which implements the ExecutorService interface 11 May

31 Executor: Advanced Implementations Executors.newFixedThreadPool Threads are created up to a fixed number Threads which die due to an unexpected exception are replaced Executors.newCachedThreadPool Creates new threads as needed, reusing previously constructed threads if they are available Executors.newSingleThreadExecutor Uses single worker thread Worker thread is replaced if an unexpected exception occurs Executors.newScheduledThreadPool Creates a ScheduledExecutorService which supports Periodic tasks (scheduleatfixedrate / schedulewithfixeddelay) Delayed tasks (schedule) 11 May

32 Executor Framework Example: Matrix Multiplication: c = a * b private static void computeproductparallel(int nt, final int[][] a, final int[][] b, final int[][] c) throws InterruptedException { ExecutorService ex = Executors.newFixedThreadPool(nt); for (int i = 0; i < N; i++) { ex.execute(new ComputeRow(i, a, b, c)); ex.shutdown(); // Graceful shutdown: // - finish pending tasks // - do not accept new ones ex.awaittermination(1, TimeUnit.HOURS); // awaits until executor is terminated Do not call it with computeproductparallel(n, a, b, a) // A = A*B 11 May

33 Result-bearing tasks: Callable & Future Callable: Task with a result / exception interface Callable<V> { V call() throws Exception; Future: represents lifecycle of a task interface Future<V> { boolean cancel(boolean mayinterruptifrunning); boolean iscancelled(); boolean isdone(); V get() throws InterruptedException, ExecutionException, CancellationException; V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, CancellationException, TimeoutException; 11 May

34 Callable & Future Submitting tasks interface ExecutorService extends Executor { //... Lifecycle methods <T> Future<T> submit(callable<t> task); Future<?> submit(runnable task); <T> Future<T> submit(runnable task, T result); <T> List<Future<T>> invokeall( Collection<? extends Callable<T>> tasks) throws InterruptedException; <T> T invokeany( Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException; 11 May

35 Callable & Future States of a Task created submitted started completed get() If completed: returns immediately (returns result or throws ExecutionException) If not completed: method call blocks If terminates regularly If terminates with an exception If cancelled If thread calling get was interrupted => result => ExecutionException => CancellationException => InterruptedException 11 May

36 Callable & Future Example: Matrix Multiplication (supports A = A*B) private static void computeproductparallel(int nt, final int[][] a, final int[][] b, final int[][] c) throws InterruptedException, ExecutionException { ExecutorService ex = Executors.newFixedThreadPool(nt); List<ComputeRow> tasks = new ArrayList<ComputeRow>(N); for (int i = 0; i < N; i++) { tasks.add(new ComputeRow(i, a, b)); List<Future<int[]>> result = ex.invokeall(tasks); // something else could be done for(int i=0; i<n; i++) { c[i] = result.get(i).get(); 11 May

Final Concurrency. Oleg October 27, 2014

Final Concurrency. Oleg October 27, 2014 Final Concurrency Oleg Šelajev @shelajev oleg@zeroturnaround.com October 27, 2014 Feedbacks Task Executors Fork-Join framework Completable Future Agenda 2 HOMEWORK 4 FEEDBACK THREAD LOCAL VARIABLES TASK

More information

[module lab 1.2] STRUCTURING PROGRAMS IN TASKS

[module lab 1.2] STRUCTURING PROGRAMS IN TASKS v1.0 Sistemi Concorrenti e di Rete LS II Facoltà di Ingegneria - Cesena a.a 2008/2009 [module lab 1.2] STRUCTURING PROGRAMS IN TASKS 1 STRUCTURING CONCURRENT PROGRAMS INTO TASKS Task concept abstract,

More information

SUMMARY FUTURES CALLABLES CONCURRENT PROGRAMMING THREAD S ADVANCED CONCEPTS

SUMMARY FUTURES CALLABLES CONCURRENT PROGRAMMING THREAD S ADVANCED CONCEPTS SUMMARY CONCURRENT PROGRAMMING THREAD S ADVANCED CONCEPTS Callable tasks Futures Executors Executor services Deadlocks PROGRAMMAZIONE CONCORRENTE E DISTR. Università degli Studi di Padova Dipartimento

More information

Parallel Programming Practice

Parallel Programming Practice Parallel Programming Practice Threads and Tasks Susanne Cech Previtali Thomas Gross Last update: 2009-10-29, 09:12 Thread objects java.lang.thread Each thread is associated with an instance of the class

More information

Parallel Programming Practice

Parallel Programming Practice Parallel Programming Practice Threads and Tasks Susanne Cech Previtali Thomas Gross Last update: 2009-10-29, 09:12 Thread objects java.lang.thread Each thread is associated with an instance of the class

More information

Concurrency in Object Oriented Programs 4. Object-Oriented Software Development COMP4001 CSE UNSW Sydney Lecturer: John Potter

Concurrency in Object Oriented Programs 4. Object-Oriented Software Development COMP4001 CSE UNSW Sydney Lecturer: John Potter Concurrency in Object Oriented Programs 4 Object-Oriented Software Development COMP4001 CSE UNSW Sydney Lecturer: John Potter Outline Thread Control Tasks and Task Control Finding and Exploiting Parallelism

More information

The Java ExecutorService (Part 1)

The Java ExecutorService (Part 1) The Java ExecutorService (Part 1) Douglas C. Schmidt d.schmidt@vanderbilt.edu www.dre.vanderbilt.edu/~schmidt Institute for Software Integrated Systems Vanderbilt University Nashville, Tennessee, USA Learning

More information

Programmazione Avanzata e Paradigmi Ingegneria e Scienze Informatiche - UNIBO a.a 2013/2014 Lecturer: Alessandro Ricci

Programmazione Avanzata e Paradigmi Ingegneria e Scienze Informatiche - UNIBO a.a 2013/2014 Lecturer: Alessandro Ricci v1.0 20130510 Programmazione Avanzata e Paradigmi Ingegneria e Scienze Informatiche - UNIBO a.a 2013/2014 Lecturer: Alessandro Ricci [module lab 3.1] TASK FRAMEWORKS 1 STRUCTURING CONCURRENT PROGRAMS INTO

More information

CST242 Concurrency Page 1

CST242 Concurrency Page 1 CST242 Concurrency Page 1 1 2 3 4 5 6 7 9 Concurrency CST242 Concurrent Processing (Page 1) Only computers with multiple processors can truly execute multiple instructions concurrently On single-processor

More information

Design Patterns and Frameworks Command

Design Patterns and Frameworks Command Design Patterns and Frameworks Command Oliver Haase Oliver Haase Emfra Command 1/13 Description Classification: Object-based behavioral pattern Purpose: Encapsulate a command as an object. Allows to dynamically

More information

[module lab 2.2] GUI FRAMEWORKS & CONCURRENCY

[module lab 2.2] GUI FRAMEWORKS & CONCURRENCY v1.0 BETA Sistemi Concorrenti e di Rete LS II Facoltà di Ingegneria - Cesena a.a 2008/2009 [module lab 2.2] GUI FRAMEWORKS & CONCURRENCY 1 GUI FRAMEWORKS & CONCURRENCY Once upon a time GUI applications

More information

Concurrency Utilities: JSR-166

Concurrency Utilities: JSR-166 Concurrency Concurrency Utilities: JSR-166 Enables development of simple yet powerful multi-threaded applications > Like Collection provides rich data structure handling capability Beat C performance in

More information

Charlie Garrod Bogdan Vasilescu

Charlie Garrod Bogdan Vasilescu Principles of So3ware Construc9on: Objects, Design, and Concurrency Part 4: Concurrency Introduc9on to concurrency, part 4 Design paderns and frameworks for concurrency Charlie Garrod Bogdan Vasilescu

More information

CONCURRENT API AND PARALLEL PROGRAMMING

CONCURRENT API AND PARALLEL PROGRAMMING MODULE 11 CONCURRENT API AND PARALLEL PROGRAMMING Module 11.A THREAD MODEL: RUNNABLE, CALLABLE, FUTURE, FUTURETASK Threads > What are threads? Threads are a virtual CPU. > The three parts of at thread

More information

LAMBDA EXPRESSIONS. Summer 2018

LAMBDA EXPRESSIONS. Summer 2018 LAMBDA EXPRESSIONS Summer 2018 LAMBDA EXPRESSIONS USES Introduced in Java SE 8, lambda expressions are a way to create single-method classes in your code in a much less cumbersome manner than anonymous

More information

LAMBDA EXPRESSIONS AND STREAMS API

LAMBDA EXPRESSIONS AND STREAMS API Java 8 LAMBDA EXPRESSIONS AND STREAMS API An Introduction Methods As Data 2 @FunctionalInterface public interface Runnable { public abstract void run(); public interface ActionListener extends EventListener

More information

Principles of Software Construction: Objects, Design and Concurrency. The Perils of Concurrency, part 4 Can't live with it. Can't live without it.

Principles of Software Construction: Objects, Design and Concurrency. The Perils of Concurrency, part 4 Can't live with it. Can't live without it. Principles of Software Construction: Objects, Design and Concurrency 15-214 toad The Perils of Concurrency, part 4 Can't live with it. Can't live without it. Fall 2012 Jonathan Aldrich Charlie Garrod School

More information

Lambdas in Java 8. Start programming in a more functional style

Lambdas in Java 8. Start programming in a more functional style Lambdas in Java 8 Start programming in a more functional style Background Who am I? Tobias Coetzee I m a Technical Lead at BBD I present the Java Expert Level Certifications at BBD (EJB, JPA, etc.) I m

More information

JSR 236 Status Jan 28, 2013

JSR 236 Status Jan 28, 2013 JSR 236 Status Jan 28, 2013 Anthony Lai Agenda Introduction Overview Current Status 2 Introduction Provides asynchronous capabilities to Java EE application components, using extension

More information

-Aditya Bhave CSCI-5448 Graduate Presentation

-Aditya Bhave CSCI-5448 Graduate Presentation -Aditya Bhave CSCI-5448 Graduate Presentation 04-01-2011 MSEE at CU finishing up in Summer 11 Work full time at Alticast Inc Background in Embedded Systems Media Processing Middleware Cable TV industry

More information

Chair of Software Engineering. Java and C# in depth. Carlo A. Furia, Marco Piccioni, Bertrand Meyer. Java: concurrency

Chair of Software Engineering. Java and C# in depth. Carlo A. Furia, Marco Piccioni, Bertrand Meyer. Java: concurrency Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer Java: concurrency Outline Java threads thread implementation sleep, interrupt, and join threads that return values Thread synchronization

More information

Principles of Software Construction: Objects, Design, and Concurrency. Concurrency: More Design Tradeoffs School of Computer Science

Principles of Software Construction: Objects, Design, and Concurrency. Concurrency: More Design Tradeoffs School of Computer Science Principles of Software Construction: Objects, Design, and Concurrency Concurrency: More Design Tradeoffs Christian Kästner Bogdan Vasilescu School of Computer Science 1 2 So far on concurrency Primitives

More information

Principles of Software Construction: Objects, Design, and Concurrency. The Perils of Concurrency, Part 3 Can't live with it. Can't live without it.

Principles of Software Construction: Objects, Design, and Concurrency. The Perils of Concurrency, Part 3 Can't live with it. Can't live without it. Principles of Software Construction: Objects, Design, and Concurrency The Perils of Concurrency, Part 3 Can't live with it. Can't live without it. Fall 2014 Charlie Garrod Jonathan Aldrich School of Computer

More information

New Features in Java 8

New Features in Java 8 New Features in Java 8 Lambda expressions Functional interfaces Streaming support for Collections Lambda expressions Are a block of java code with parameters Can be assigned to variables Can be executed

More information

The Java FutureTask. Douglas C. Schmidt

The Java FutureTask. Douglas C. Schmidt The Java FutureTask Douglas C. Schmidt d.schmidt@vanderbilt.edu www.dre.vanderbilt.edu/~schmidt Institute for Software Integrated Systems Vanderbilt University Nashville, Tennessee, USA Learning Objectives

More information

Fontys Hogeschool voor Techniek en Logistiek. March 13, 2018

Fontys Hogeschool voor Techniek en Logistiek. March 13, 2018 Java 8 s and Java 8 Fontys Hogeschool voor Techniek en Logistiek March 13, 2018 and? /FHTenL s and Java 8 March 13, 2018 1/34 talk The other anonymous and? Java 8 and? /FHTenL s and Java 8 March 13, 2018

More information

Principles of Software Construction: Objects, Design and Concurrency. The Perils of Concurrency, Part 3 Can't live with it. Cant live without it.

Principles of Software Construction: Objects, Design and Concurrency. The Perils of Concurrency, Part 3 Can't live with it. Cant live without it. Principles of Software Construction: Objects, Design and Concurrency 15-214 toad The Perils of Concurrency, Part 3 Can't live with it. Cant live without it. Fall 2013 Jonathan Aldrich Charlie Garrod School

More information

Software Design: Copy & Paste

Software Design: Copy & Paste Software Design: Copy & Paste Your assistant for this week Velko Vechev E-mail: velko.vechev@inf.ethz.ch Office: CNB H 100.9 You can simply stop by. You can also drop me a short e-mail to check if I m

More information

COMP 213. Advanced Object-oriented Programming. Lecture 23. Shared Variables and Synchronization

COMP 213. Advanced Object-oriented Programming. Lecture 23. Shared Variables and Synchronization COMP 213 Advanced Object-oriented Programming Lecture 23 Shared Variables and Synchronization Communicating Threads In the previous lecture, we saw an example of a multi-threaded program where three threads

More information

Using Lambdas to Write Mixins in Java 8

Using Lambdas to Write Mixins in Java 8 Using Lambdas to Write Mixins in Java 8 Dr Heinz M. Kabutz heinz@javaspecialists.eu Last updated 2015-04-21 2014-2015 Heinz Kabutz All Rights Reserved Copyright Notice l 2014-2015 Heinz Kabutz, All Rights

More information

301AA - Advanced Programming [AP-2017]

301AA - Advanced Programming [AP-2017] 301AA - Advanced Programming [AP-2017] Lecturer: Andrea Corradini andrea@di.unipi.it Tutor: Lillo GalleBa galleba@di.unipi.it Department of Computer Science, Pisa Academic Year 2017/18 AP-2017-15: Recursion,

More information

Principles of Programming Languages

Principles of Programming Languages Principles of Programming Languages h"p://www.di.unipi.it/~andrea/dida2ca/plp- 15/ Prof. Andrea Corradini Department of Computer Science, Pisa Lesson 30 Java 8! Lambdas and streams in Java 8 1 Java 8:

More information

Overview of Java 8 Functional Interfaces

Overview of Java 8 Functional Interfaces Overview of Java 8 Functional Interfaces Douglas C. Schmidt d.schmidt@vanderbilt.edu www.dre.vanderbilt.edu/~schmidt Professor of Computer Science Institute for Software Integrated Systems Vanderbilt University

More information

Charlie Garrod Michael Hilton

Charlie Garrod Michael Hilton Principles of So3ware Construc9on: Objects, Design, and Concurrency Part 5: Concurrency Introduc9on to concurrency, part 4 Concurrency frameworks Charlie Garrod Michael Hilton School of Computer Science

More information

Project Lambda in Java SE 8

Project Lambda in Java SE 8 Project Lambda in Java SE 8 Daniel Smith Java Language Designer 1 The following is intended to outline our general product direction. It is intended for information purposes only, and may not be incorporated

More information

MultiThreading 07/01/2013. Session objectives. Introduction. Introduction. Advanced Java Programming Course

MultiThreading 07/01/2013. Session objectives. Introduction. Introduction. Advanced Java Programming Course Advanced Java Programming Course MultiThreading By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City Session objectives Introduction Creating thread Thread class

More information

Advanced Java Programming Course. MultiThreading. By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City

Advanced Java Programming Course. MultiThreading. By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City Advanced Java Programming Course MultiThreading By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City Session objectives Introduction Creating thread Thread class

More information

UNIT V CONCURRENT PROGRAMMING

UNIT V CONCURRENT PROGRAMMING UNIT V CONCURRENT PROGRAMMING Multi-Threading: Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run concurrently. Each part of such

More information

Java Workshop Lambda Expressions

Java Workshop Lambda Expressions Java Workshop Lambda Expressions AP Java Workshop 2015 Hanno Hüther and Martin Stein Agenda 1. Origin and syntax 2. History and motivation 3. Exercise 1: Refactoring to lambdas 4. Method references 5.

More information

Binghamton University. CS-140 Fall Functional Java

Binghamton University. CS-140 Fall Functional Java Functional Java 1 First Class Data We have learned how to manipulate data with programs We can pass data to methods via arguments We can return data from methods via return types We can encapsulate data

More information

Paradigmas de Computação Paralela

Paradigmas de Computação Paralela Paradigmas de Computação Paralela Concurrent/Parallel Programming in OO /Java João Luís Ferreira Sobral jls@... Specification of concurrency/parallelism Benefits from concurrent programming Programs that

More information

Multithreading. Introduction and Basics. Classical Model. New Model. Summary. Multithreading Basics Problems with Multithreading

Multithreading. Introduction and Basics. Classical Model. New Model. Summary. Multithreading Basics Problems with Multithreading Multithreading Introduction and Basics Multithreading Basics Problems with Multithreading Classical Model Synchronization Threads und Swing New Model Executors and Futures Synchronization Concurrent Collections

More information

Overview. Topics in This Section

Overview. Topics in This Section Topics in This Section 4 Why threads? Basic approach Make a task list with Executors.newFixedThreadPool Add tasks to list with tasklist.execute(somerunnable) Three variations on the theme Separate classes

More information

CPSC 213. Introduction to Computer Systems. Reading. Thread. The Virtual Processor. Virtual Processors. Unit 2b. Text. An abstraction for execution

CPSC 213. Introduction to Computer Systems. Reading. Thread. The Virtual Processor. Virtual Processors. Unit 2b. Text. An abstraction for execution Reading Text CPSC 213 2ed: 12.3 1ed: 13.3 Introduction to Computer Systems Unit 2b Virtual Processors The Virtual Processor 1 Thread 2 Originated with Edsger Dijkstra in the THE Operating System in The

More information

Chapter 4 Defining Classes I

Chapter 4 Defining Classes I Chapter 4 Defining Classes I This chapter introduces the idea that students can create their own classes and therefore their own objects. Introduced is the idea of methods and instance variables as the

More information

Introducing Scala-like function types into Java-TX

Introducing Scala-like function types into Java-TX Introducing Scala-like function types into Java-TX ManLang 2017 Martin Plümicke Andreas Stadelmeier www.dhbw-stuttgart.de/horb Overview 1 Type of lambda expressions in Java-8 2 Introducing real function

More information

CmpSci 187: Programming with Data Structures Spring 2015

CmpSci 187: Programming with Data Structures Spring 2015 CmpSci 187: Programming with Data Structures Spring 2015 Lecture #13, Concurrency, Interference, and Synchronization John Ridgway March 12, 2015 Concurrency and Threads Computers are capable of doing more

More information

Using the Executor Framework to Implement AEH in the RTSJ

Using the Executor Framework to Implement AEH in the RTSJ Using the Executor Framework to Implement AEH in the RTSJ Table of Contents MinSeong Kim & Andy Wellings Role of AEH in the RTSJ AEH Facility in the RTSJ Implementation Discussion Limitations of AEH The

More information

Java EE 7 Recipes for Concurrency. Presented By: Josh Juneau Author and Application Developer

Java EE 7 Recipes for Concurrency. Presented By: Josh Juneau Author and Application Developer Java EE 7 Recipes for Concurrency Presented By: Josh Juneau Author and Application Developer About Me Josh Juneau Day Job: Developer and DBA @ Fermilab Night/Weekend Job: Technical Writer - Java Magazine

More information

Using Lambdas to Write Mixins in Java 8

Using Lambdas to Write Mixins in Java 8 Using Lambdas to Write Mixins in Java 8 Dr Heinz M. Kabutz heinz@javaspecialists.eu Last updated 2014-11-12 2014 Heinz Kabutz All Rights Reserved Copyright Notice l 2014 Heinz Kabutz, All Rights Reserved

More information

CS 351 Design of Large Programs Threads and Concurrency

CS 351 Design of Large Programs Threads and Concurrency CS 351 Design of Large Programs Threads and Concurrency Brooke Chenoweth University of New Mexico Spring 2018 Concurrency in Java Java has basic concurrency support built into the language. Also has high-level

More information

Threads Questions Important Questions

Threads Questions Important Questions Threads Questions Important Questions https://dzone.com/articles/threads-top-80-interview https://www.journaldev.com/1162/java-multithreading-concurrency-interviewquestions-answers https://www.javatpoint.com/java-multithreading-interview-questions

More information

Simpler, Faster, Better: Concurrency Utilities in JDK Software Version 5.0

Simpler, Faster, Better: Concurrency Utilities in JDK Software Version 5.0 Simpler, Faster, Better: Concurrency Utilities in JDK Software Version 5.0 Brian Goetz Principal Consultant, Quiotix Corp David Holmes Staff Engineer, Sun Microsystems, Inc. TS-4915 2006 JavaOne SM Conference

More information

Computation Abstractions. Processes vs. Threads. So, What Is a Thread? CMSC 433 Programming Language Technologies and Paradigms Spring 2007

Computation Abstractions. Processes vs. Threads. So, What Is a Thread? CMSC 433 Programming Language Technologies and Paradigms Spring 2007 CMSC 433 Programming Language Technologies and Paradigms Spring 2007 Threads and Synchronization May 8, 2007 Computation Abstractions t1 t1 t4 t2 t1 t2 t5 t3 p1 p2 p3 p4 CPU 1 CPU 2 A computer Processes

More information

Lecture 03: Thread API (continue)

Lecture 03: Thread API (continue) Lecture 03: Thread API (continue) SSC2 Behzad Bordbar School of Computer Science, University of Birmingham, UK Lecture 03 1 Recap Extending Thread or implementing Runnable Thread terminology Stopping Threads

More information

CONTENTS. Chapter 1 Getting Started with Java SE 6 1. Chapter 2 Exploring Variables, Data Types, Operators and Arrays 13

CONTENTS. Chapter 1 Getting Started with Java SE 6 1. Chapter 2 Exploring Variables, Data Types, Operators and Arrays 13 CONTENTS Chapter 1 Getting Started with Java SE 6 1 Introduction of Java SE 6... 3 Desktop Improvements... 3 Core Improvements... 4 Getting and Installing Java... 5 A Simple Java Program... 10 Compiling

More information

Overview of Java Threads (Part 3)

Overview of Java Threads (Part 3) Overview of Java Threads (Part 3) Douglas C. Schmidt d.schmidt@vanderbilt.edu www.dre.vanderbilt.edu/~schmidt Institute for Software Integrated Systems Vanderbilt University Nashville, Tennessee, USA Learning

More information

Java SE 8: Lambda Expressions And The Stream API

Java SE 8: Lambda Expressions And The Stream API Java SE 8: Lambda Expressions And The Stream API Simon Ritter Head of Java Technology Evangelism Java Product Management Java Day Tokyo 2015 April 8, 2015 Safe Harbor Statement The following is intended

More information

B2.52-R3: INTRODUCTION TO OBJECT ORIENTATED PROGRAMMING THROUGH JAVA

B2.52-R3: INTRODUCTION TO OBJECT ORIENTATED PROGRAMMING THROUGH JAVA B2.52-R3: INTRODUCTION TO OBJECT ORIENTATED PROGRAMMING THROUGH JAVA NOTE: 1. There are TWO PARTS in this Module/Paper. PART ONE contains FOUR questions and PART TWO contains FIVE questions. 2. PART ONE

More information

Concurrency CSCI 201 Principles of Software Development

Concurrency CSCI 201 Principles of Software Development Concurrency CSCI 201 Principles of Software Development Jeffrey Miller, Ph.D. jeffrey.miller@usc.edu Synchronization Outline USC CSCI 201L Motivation for Synchronization Thread synchronization is used

More information

Advanced programming for Java platform. Introduction

Advanced programming for Java platform. Introduction Advanced programming for Java platform Introduction About course Petr Hnětynka hnetynka@d3s.mff.cuni.cz http://d3s.mff.cuni.cz/teaching/vsjava/ continuation of "Java (NPRG013)" basic knowledge of Java

More information

AP CS Unit 11: Graphics and Events

AP CS Unit 11: Graphics and Events AP CS Unit 11: Graphics and Events This packet shows how to create programs with a graphical interface in a way that is consistent with the approach used in the Elevens program. Copy the following two

More information

PIC 20A Anonymous classes, Lambda Expressions, and Functional Programming

PIC 20A Anonymous classes, Lambda Expressions, and Functional Programming PIC 20A Anonymous classes, Lambda Expressions, and Functional Programming Ernest Ryu UCLA Mathematics Last edited: December 8, 2017 Introductory example When you write an ActionListener for a GUI, you

More information

Daemon thread, 7 Deadlock, 27

Daemon thread, 7 Deadlock, 27 Index A ArrayBlockingQueue, 127 128 Atomic variables AtomicLong, 132 contention-reduction techniques, 132 counters and sequence generators, 131 getnextid() class, 131 intrinsic lock, 131 java.util.concurrent.atomic

More information

Multithreaded Programming Part II. CSE 219 Stony Brook University, Department of Computer Science

Multithreaded Programming Part II. CSE 219 Stony Brook University, Department of Computer Science Multithreaded Programming Part II CSE 219 Stony Brook University, Thread Scheduling In a Java application, main is a thread on its own Once multiple threads are made Runnable the thread scheduler of the

More information

What is a thread anyway?

What is a thread anyway? Concurrency in Java What is a thread anyway? Smallest sequence of instructions that can be managed independently by a scheduler There can be multiple threads within a process Threads can execute concurrently

More information

CONCURRENCY IN JAVA Course Parallel Computing

CONCURRENCY IN JAVA Course Parallel Computing CONCURRENCY IN JAVA Course Parallel Computing Wolfgang Schreiner Research Institute for Symbolic Computation (RISC) Wolfgang.Schreiner@risc.jku.at http://www.risc.jku.at Java on a NUMA Architecture Loading

More information

Design Patterns. Command. Oliver Haase

Design Patterns. Command. Oliver Haase Design Patterns Command Oliver Haase 1 Description Purpose: Encapsulate a command as an object. Allows to dynamically configure an invoker with a command object. Invoker can invoke command without knowing

More information

Java Threads. COMP 585 Noteset #2 1

Java Threads. COMP 585 Noteset #2 1 Java Threads The topic of threads overlaps the boundary between software development and operation systems. Words like process, task, and thread may mean different things depending on the author and the

More information

Java Technologies. Lecture IV. Valdas Rapševičius

Java Technologies. Lecture IV. Valdas Rapševičius Preparation of the material was supported by the project Increasing Internationality in Study Programs of the Department of Computer Science II, project number VP1 2.2 ŠMM-07-K-02-070, funded by The European

More information

Concurrent Programming using Threads

Concurrent Programming using Threads Concurrent Programming using Threads Threads are a control mechanism that enable you to write concurrent programs. You can think of a thread in an object-oriented language as a special kind of system object

More information

[module lab 1.3] CANCELLATION AND SHUTDOWN

[module lab 1.3] CANCELLATION AND SHUTDOWN v1.0 BETA Sistemi Concorrenti e di Rete LS II Facoltà di Ingegneria - Cesena a.a 2008/2009 [module lab 1.3] CANCELLATION AND SHUTDOWN 1 STOPPING THREADS AND TASKS An activity is cancellable if external

More information

Chapter 4: Threads. Operating System Concepts 9 th Edit9on

Chapter 4: Threads. Operating System Concepts 9 th Edit9on Chapter 4: Threads Operating System Concepts 9 th Edit9on Silberschatz, Galvin and Gagne 2013 Chapter 4: Threads 1. Overview 2. Multicore Programming 3. Multithreading Models 4. Thread Libraries 5. Implicit

More information

CS370 Operating Systems

CS370 Operating Systems CS370 Operating Systems Colorado State University Yashwant K Malaiya Spring 2018 Lecture 8 Threads and Scheduling Slides based on Text by Silberschatz, Galvin, Gagne Various sources 1 1 FAQ How many threads

More information

Comp-304 : Command Lecture 22. Alexandre Denault Original notes by Marc Provost and Hans Vangheluwe Computer Science McGill University Fall 2007

Comp-304 : Command Lecture 22. Alexandre Denault Original notes by Marc Provost and Hans Vangheluwe Computer Science McGill University Fall 2007 Command Comp-304 : Command Lecture 22 Alexandre Denault Original notes by Marc Provost and Hans Vangheluwe Computer Science McGill University Fall 2007 Classic Example Problem User interface toolkit includes

More information

Chapter 6 Introduction to Defining Classes

Chapter 6 Introduction to Defining Classes Introduction to Defining Classes Fundamentals of Java: AP Computer Science Essentials, 4th Edition 1 Objectives Design and implement a simple class from user requirements. Organize a program in terms of

More information

Thread Pools SE 441. Prof. Bullinger

Thread Pools SE 441. Prof. Bullinger Thread Pools SE 441 Prof. Bullinger Thread Pools Thread Pool Limitations Sizing Thread Pools ThreadPoolExecutor Queuing Tasks Parallelizing Loops Thread Pool Limitations Task Dependencies Different types

More information

Introduction to Functional Programming in Java 8

Introduction to Functional Programming in Java 8 1 Introduction to Functional Programming in Java 8 Java 8 is the current version of Java that was released in March, 2014. While there are many new features in Java 8, the core addition is functional programming

More information

Advanced Programming Concurrency

Advanced Programming Concurrency Advanced Programming Concurrency Concurrent Programming Until now, a program was a sequence of operations, executing one after another. In a concurrent program, several sequences of operations may execute

More information

CS 450 Operating System Week 4 Lecture Notes

CS 450 Operating System Week 4 Lecture Notes CS 450 Operating System Week 4 Lecture Notes Reading: Operating System Concepts (7 th Edition) - Silberschatz, Galvin, Gagne Chapter 5 - Pages 129 147 Objectives: 1. Explain the main Objective of Threads

More information

Java Threads and intrinsic locks

Java Threads and intrinsic locks Java Threads and intrinsic locks 1. Java and OOP background fundamentals 1.1. Objects, methods and data One significant advantage of OOP (object oriented programming) is data encapsulation. Each object

More information

EI 338: Computer Systems Engineering (Operating Systems & Computer Architecture)

EI 338: Computer Systems Engineering (Operating Systems & Computer Architecture) EI 338: Computer Systems Engineering (Operating Systems & Computer Architecture) Dept. of Computer Science & Engineering Chentao Wu wuct@cs.sjtu.edu.cn Download lectures ftp://public.sjtu.edu.cn User:

More information

Concurrent Objects and Linearizability

Concurrent Objects and Linearizability Chapter 3 Concurrent Objects and Linearizability 3.1 Specifying Objects An object in languages such as Java and C++ is a container for data. Each object provides a set of methods that are the only way

More information

Java SE 8 Programmer I and II Syballus( Paper codes : 1z0-808 & 1z0-809)

Java SE 8 Programmer I and II Syballus( Paper codes : 1z0-808 & 1z0-809) Page1 Java SE 8 Programmer 1, also called OCJA 8.0 Exam Number: 1Z0-808 Associated Certifications: Oracle Certified Associate, Java SE 8 Programmer Java Basics Highlights of the Certifications Define the

More information

Monitors CSCI 201 Principles of Software Development

Monitors CSCI 201 Principles of Software Development Monitors CSCI 201 Principles of Software Development Jeffrey Miller, Ph.D. jeffrey.miller@usc.edu Outline Monitors Program USC CSCI 201L Monitor Overview A monitor is an object with mutual exclusion and

More information

Only one thread can own a specific monitor

Only one thread can own a specific monitor Java 5 Notes Threads inherit their priority and daemon properties from their creating threads The method thread.join() blocks and waits until the thread completes running A thread can have a name for identification

More information

CSCI 136 Written Exam #2 Fundamentals of Computer Science II Spring 2015

CSCI 136 Written Exam #2 Fundamentals of Computer Science II Spring 2015 CSCI 136 Written Exam #2 Fundamentals of Computer Science II Spring 2015 Name: This exam consists of 6 problems on the following 6 pages. You may use your double- sided hand- written 8 ½ x 11 note sheet

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 35 November 29, 2017 Swing II: Building GUIs Inner Classes Chapter 29 Announcements Game Project Complete Code Due: December 11 th NO LATE SUBMISSIONS

More information

COMP 322: Fundamentals of Parallel Programming. Lecture 30: Java Synchronizers, Dining Philosophers Problem

COMP 322: Fundamentals of Parallel Programming. Lecture 30: Java Synchronizers, Dining Philosophers Problem COMP 322: Fundamentals of Parallel Programming Lecture 30: Java Synchronizers, Dining Philosophers Problem Vivek Sarkar, Shams Imam Department of Computer Science, Rice University Contact email: vsarkar@rice.edu,

More information

Multitasking Multitasking allows several activities to occur concurrently on the computer. A distinction is usually made between: Process-based multit

Multitasking Multitasking allows several activities to occur concurrently on the computer. A distinction is usually made between: Process-based multit Threads Multitasking Multitasking allows several activities to occur concurrently on the computer. A distinction is usually made between: Process-based multitasking Thread-based multitasking Multitasking

More information

Java SE 8 Programming

Java SE 8 Programming Java SE 8 Programming Training Calendar Date Training Time Location 16 September 2019 5 Days Bilginç IT Academy 28 October 2019 5 Days Bilginç IT Academy Training Details Training Time : 5 Days Capacity

More information

Commands. Written commands can be reused, cataloged, etc. Sometimes they also contain "undo" commands, too.

Commands. Written commands can be reused, cataloged, etc. Sometimes they also contain undo commands, too. Commands A command is something you want someone else to perform. Instead of directly issuing a command, we can write it down and give it to someone to perform. Written commands can be reused, cataloged,

More information

CMSC 330: Organization of Programming Languages

CMSC 330: Organization of Programming Languages CMSC 330: Organization of Programming Languages Threads Synchronization Refers to mechanisms allowing a programmer to control the execution order of some operations across different threads in a concurrent

More information

Java Barrier Synchronizers: CountDownLatch (Part 1)

Java Barrier Synchronizers: CountDownLatch (Part 1) Java Barrier Synchronizers: CountDownLatch (Part 1) Douglas C. Schmidt d.schmidt@vanderbilt.edu www.dre.vanderbilt.edu/~schmidt Institute for Software Integrated Systems Vanderbilt University Nashville,

More information

Introduction to Object-Oriented Programming

Introduction to Object-Oriented Programming Introduction to Object-Oriented Programming Lambda Expressions Christopher Simpkins chris.simpkins@gatech.edu CS 1331 (Georgia Tech) Lambda Expressions 1 / 14 Inner Classes Recall from SortTroopers.java

More information

CSC207 Week 4. Larry Zhang

CSC207 Week 4. Larry Zhang CSC207 Week 4 Larry Zhang 1 Logistics A1 Part 1, read Arnold s emails. Follow the submission schedule. Read the Q&A session in the handout. Ask questions on the discussion board. Submit on time! Don t

More information

Lambdas & Streams In JDK 8: Beyond The Basics

Lambdas & Streams In JDK 8: Beyond The Basics Lambdas & Streams In JDK 8: Beyond The Basics Simon Ritter Deputy CTO, Azul Systems @speakjava azul.com Copyright Azul Systems 2015 1 A clever man learns from his mistakes......a wise man learns from other

More information

VALLIAMMAI ENGINEERING COLLEGE

VALLIAMMAI ENGINEERING COLLEGE VALLIAMMAI ENGINEERING COLLEGE SRM Nagar, Kattankulathur 60 0 DEPARTMENT OF INFORMATION TECHNOLOGY QUESTION BANK III SEMESTER CS89- Object Oriented Programming Regulation 07 Academic Year 08 9 Prepared

More information

Grand Central Dispatch and NSOperation. CSCI 5828: Foundations of Software Engineering Lecture 28 12/03/2015

Grand Central Dispatch and NSOperation. CSCI 5828: Foundations of Software Engineering Lecture 28 12/03/2015 Grand Central Dispatch and NSOperation CSCI 5828: Foundations of Software Engineering Lecture 28 12/03/2015 1 Credit Where Credit Is Due Most of the examples in this lecture were inspired by example code

More information