11 Other Programming Aspects Dr. Miguel A. Labrador Department of Computer Science & Engineering

Slides:



Advertisements
Similar presentations
Java How to Program, 9/e CET 3640 Professor: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Advertisements

Multithreading The objectives of this chapter are:
Concurrency…leading up to writing a web crawler. Web crawlers.
CS220 Software Development Lecture: Multi-threading A. O’Riordan, 2009.
Chapter 11 Operating Systems
Definitions Process – An executing program
Multithreading in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
1 Threads Chapter 4 Reading: 4.1,4.4, Process Characteristics l Unit of resource ownership - process is allocated: n a virtual address space to.
Multithreading in Java Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
Fundamentals of Python: From First Programs Through Data Structures
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.
1 Advanced Computer Programming Concurrency Multithreaded Programs Copyright © Texas Education Agency, 2013.
Java Programming: Advanced Topics
Object Oriented Analysis & Design SDL Threads. Contents 2  Processes  Thread Concepts  Creating threads  Critical sections  Synchronizing threads.
Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read.
Lecture 5 : JAVA Thread Programming Courtesy : MIT Prof. Amarasinghe and Dr. Rabbah’s course note.
Multi-Threaded Application CSNB534 Asma Shakil. Overview Software applications employ a strategy called multi- threaded programming to split tasks into.
Quick overview of threads in Java Babak Esfandiari (extracted from Qusay Mahmoud’s slides)
Multithreading in Java Project of COCS 513 By Wei Li December, 2000.
Java Threads 11 Threading and Concurrent Programming in Java Introduction and Definitions D.W. Denbo Introduction and Definitions D.W. Denbo.
Today’s Agenda  Quick Review  Finish Java Threads  The CS Problem Advanced Topics in Software Engineering 1.
© 2004, D. J. Foreman 2-1 Concurrency, Processes and Threads.
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.
Threading Eriq Muhammad Adams J
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
ICS 313: Programming Language Theory Chapter 13: Concurrency.
Introduction to Threads Session 01 Java Simplified / Session 14 / 2 of 28 Objectives Define a thread Define multithreading List benefits of multithreading.
Multithreading in JAVA
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.
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.
Department of Computer Science and Software Engineering
CMSC 330: Organization of Programming Languages Threads.
1 OS Review Processes and Threads Chi Zhang
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 & Synchronized Algoritma Pemrograman 3 Sistem Komputer – S1 Universitas Gunadarma 1.
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.
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.
1 Threads in Java Jingdi Wang. 2 Introduction A thread is a single sequence of execution within a program Multithreading involves multiple threads of.
Concurrency in Java MD. ANISUR RAHMAN. slide 2 Concurrency  Multiprogramming  Single processor runs several programs at the same time  Each program.
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.
Java Thread Programming
Multithreading The objectives of this chapter are:
Multithreading / Concurrency
Processes and threads.
Process Management Process Concept Why only the global variables?
Multi Threading.
Java Multithreading.
Multithreading.
Concurrency, Processes and Threads
Multithreaded Programming in Java
Lecture 21 Concurrency Introduction
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.
Java Based Techhnology
Multithreading.
Multithreaded Programming
Threads Chapter 4.
Multithreading in java.
Threads and Multithreading
Foundations and Definitions
Concurrency, Processes and Threads
Multithreading The objectives of this chapter are:
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

11 Other Programming Aspects Dr. Miguel A. Labrador Department of Computer Science & Engineering

2 Copyright© Dr. Miguel A. Labrador 2 2 Outline Memory management Concurrency Dynamic linking Energy management

3 Copyright© Dr. Miguel A. Labrador 3 3 Memory Management Memory is very limited in cellular phones –Managed and used efficiently Recall Heap and Stack –Stack is a very-well structured memory to store information about each thread –Heap is a pool of non-structured memory for general purpose Stack is managed by the system; Heap is managed by the programmer

4 Copyright© Dr. Miguel A. Labrador 4 4 Memory Use Guidelines Release memory as soon as possible; allocate memory as late as possible –More memory is available for new objects Run programs from ROM when possible to save RAM Select the right structure –Native types save memory versus objects Declare variables in best order –In groups according to the word alignment Use arrays instead of vectors –Vector uses objects Consider using stringBuffer instead of String –Concatenating data using String and the “+” operator consumes more memory than the StringBuffer and the append method

5 Copyright© Dr. Miguel A. Labrador 5 5 Memory Use Guidelines Use as few objects and classes as possible Deference objects –Set them to NULL when not used to be garbage collected Use the –g:none switch –Compiling without debugging information Obfuscate code –Reduce names of packages, classes, methods, variables, etc. Less fragmentation –Use linear data structures and avoid creating/destructing objects very frequently

6 Copyright© Dr. Miguel A. Labrador 6 6 Concurrency Users expect the cell phone to display images of the caller while ringing the phone, check for keyboard to accept or dismiss the call, consult your list of contacts while talking, etc. Simultaneous tasks can be accomplished by using multitasking and/or multiprocessing –Multiprocessing means that the computer has more than one processing unit and therefore can assign tasks to different processors at the same time Not usually the case of cellular phones –Multitasking is the time sharing of the processing unit The operating system scheduler assign a time slice of the processing unit to a particular task and then switches to another task, and so forth –The computer gives the impression of being working on all the tasks at the same time Multitasking is achieved by means of processes and threads

7 Copyright© Dr. Miguel A. Labrador 7 7 Processes and Threads A process is considered a self-contained execution environment –The OS assigns resources (e.g., memory) to processes An application may run in a single or multiple collaborating processes –Communicate by means of inter-process communications, such as sockets JVM usually runs as a single process Threads are the fundamental units of execution Every application has at least one thread A process may create more than one thread, each in charge of the execution of a sequential stream of instructions –Perform multiple tasks Threads also have their own execution environment or context

8 Copyright© Dr. Miguel A. Labrador 8 8 Processes and Threads A program executes multiple threads in parallel, each in charge of executing one task of the entire program With one processor, the thread scheduling mechanism switches from thread to thread so they all get a piece of the CPU’s time –Context switching Threads can be in any of the following four states –Running –Ready –Suspended –Terminated The java.lang.Thread class includes methods to handle threads –activeCount(), currentThread(), getPriority(), setPriority(), isAlive(), join(), run(), interrupt(), sleep(), start(), yield()

9 Copyright© Dr. Miguel A. Labrador 9 9 Thread’s State Machine run() Ready Suspended Running sleep(), join(), yield() Terminate() Sleep, expired, join, yield, complete Terminated start()

10 Copyright© Dr. Miguel A. Labrador 10 Copyright© Dr. Miguel A. Labrador 10 Defining and Creating Threads Two things are needed to start a new thread –An instance of the java.lang.Thread class –An object that implements the runnable interface There are two ways to create a thread –Declare a class that extends the Thread class –Define a class that implements the Runnable interface

11 Copyright© Dr. Miguel A. Labrador 11 Copyright© Dr. Miguel A. Labrador 11 Defining and Creating Threads Extending the Thread class –Thread and object are created together public class MyWorkProcess extends Thread { // Subclass of Thread public void run() {... // Here goes the thread's work }... Thread MyThread = new MyWorkProcess(); // Creates instance of Thread MyThread.start(); // Start the thread...

12 Copyright© Dr. Miguel A. Labrador 12 Copyright© Dr. Miguel A. Labrador 12 Defining and Creating Threads Using the Runnable interface –First create a runnable object –Then create instance of thread –Start the thread invoking the start method which invokes the runnable’s run() public class MyWorkProcess implements Runnable { public void run() {... // Here goes the thread's work }... MyWorkProcess MyWork = new MyWorkProcess(); // Creates a runnable object Thread MyThread = new Thread (MyWork); // Creates instance of Thread MyThread.start(); // start the thread...

13 Copyright© Dr. Miguel A. Labrador 13 Copyright© Dr. Miguel A. Labrador 13 Defining and Creating Threads Another way of using the Runnable interface Runnable theInvoker = new Runnable(){ public void run() {... // Here goes the thread's work }... Thread t = new Thread(theInvoker); t.start();...

14 Copyright© Dr. Miguel A. Labrador 14 Copyright© Dr. Miguel A. Labrador 14 Stopping Threads stop() and suspend() methods have been deprecated –Interrupt() method still available One way to terminate a thread is to use a boolean variable that will force the thread to exit the run() method If one thread uses the quit() method to stop another thread, it can use isAlive() to make sure the first thread actually stopped Terminating thread can use join() to wait until other thread stops public class MyWorkProcess implements Runnable { private boolean flag = false; public void run() { while(!flag){... // Here goes the thread's work } public void quit(){ flag = true; }

15 Copyright© Dr. Miguel A. Labrador 15 Copyright© Dr. Miguel A. Labrador 15 Sleeping Threads Sleep() method causes the thread to suspend execution for a specified period of time and make the processor available to other threads public class SleepExample implements Runnable { public void run() { for (i=0; i<=3; i++) { Thread.sleep(5000); System.out.println(i); }

16 Copyright© Dr. Miguel A. Labrador 16 Copyright© Dr. Miguel A. Labrador 16 Monitors and Locks Multithreading allows for the parallel execution of tasks –Reduces overall execution time –Makes better utilization of the hardware resources. –Introduces new problems Thread interference and memory consistency errors Thread interference may happen whenever multiple step operations coming from different threads act on the same data –If the operations overlap, there is the chance that the data may be changed in an erroneous order, therefore producing unexpected, wrong results Memory consistency errors occur when different threads have inconsistent views of what should be the same data Thread synchronization is meant to solve these problems –Utilizes the monitor to control which thread can read or write at any given time

17 Copyright© Dr. Miguel A. Labrador 17 Copyright© Dr. Miguel A. Labrador 17 Monitors and Locks Objects are synchronized by using the synchronized keyword –They lock then object in the entire block of code Synchronized word can also be used to synchronize methods Object MyObject = new Object(); void MyFunction () { synchronized (MyObject){ // Here the thread locks MyObject... //operations on the object; Here the thread holds the lock on MyObject... // Here the thread continues to hold the lock } // Here the thread releases the lock void synchronized MyFunction () { // Everything inside this block is locked... // Code implementing MyFunction() } // Lock is released

18 Copyright© Dr. Miguel A. Labrador 18 Copyright© Dr. Miguel A. Labrador 18 Monitors and Locks Thread synchronization does not guarantee the order in which the thread invoke the methods –Guarantees that only one thread at a time will be executing the method Synchronization brings other problems –Overhead Locking and unlocking takes time Deadlocks A simple technique to avoid deadlocks is to lock objects in the same order every time –Be careful when performing any operation that might take a long time to execute while holding a lock

19 Copyright© Dr. Miguel A. Labrador 19 Copyright© Dr. Miguel A. Labrador 19 Waits and Notifications Sometimes we want one thread to wait for a particular event before accessing the data –Suspend the thread Be careful in cell phones; suspended thread continue to use CPU cycles Three methods in the java.lang.Object class to suspend threads without spending energy –Wait(), notify(), notifyAll() –Thread must lock the object before invoking the wait() method –Once the thread suspends itself, it releases the object and waits for a notification or for a specific amount of time Object MyObject = new Object(); synchronized (MyObject) { try { MyObject.wait(); } catch (InterruptExeption e) { } synchronized (MyObject) {... /Some operations on object MyObject.notify(); // or notifyAll() }

20 Copyright© Dr. Miguel A. Labrador 20 Copyright© Dr. Miguel A. Labrador 20 Dynamic Linking Dynamic linking allows a programmer to develop libraries and provide services to many applications –Reduce development time: code once and use many times –Reduce programming errors –Modular applications –Can save a lot of memory as many applications use the same copy Executables and libraries reference to each other by links –Linking process performed by the linker Libraries can be linked dynamically or statically

21 Copyright© Dr. Miguel A. Labrador 21 Copyright© Dr. Miguel A. Labrador 21 Dynamic Linking In static linking libraries are instantiated at the starting time of the calling program –Stay in memory as long as the program runs In dynamic linking libraries are loaded and unloaded as needed The Java ME platform supports dynamic linking of those libraries and classes that are included in the application’s JAR file only –Applications do not interfere with each other

22 Copyright© Dr. Miguel A. Labrador 22 Copyright© Dr. Miguel A. Labrador 22 Energy Management Precious resource in cellular phones No standardized APIs to provide access to energy-related properties –Remaining battery level, screen brightness, set device or parts of the device off, hibernate, sleep –Responsibility of energy management to the programmer Programmer has indirect control through methods that act upon the device components –Opening or closing network connections to turn radio on or off –Changing GPS calculation intervals to turn GPS on or off Communication is the most expensive function in terms of energy consumption –Need to pay close attention to it

23 Copyright© Dr. Miguel A. Labrador 23 Copyright© Dr. Miguel A. Labrador 23 Energy Management Consider our tracking application that needs to send GPS fixes continuously –What communication protocol is more adequate? TCP? UDP?