230 likes | 431 Views
Other Programming Aspects. Dr. Miguel A. Labrador Department of Computer Science & Engineering labrador@csee.usf.edu http://www.csee.usf.edu/~labrador. Outline. Memory management Concurrency Dynamic linking Energy management. Memory Management.
E N D
Other Programming Aspects Dr. Miguel A. Labrador Department of Computer Science & Engineering labrador@csee.usf.edu http://www.csee.usf.edu/~labrador
Outline • Memory management • Concurrency • Dynamic linking • Energy management
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
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
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
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
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
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()
Thread’s State Machine sleep(), join(), yield() Ready Running start() Suspended run() Terminate() Sleep, expired, join, yield, complete Terminated
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
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 ...
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 } } ... MyWorkProcessMyWork = new MyWorkProcess(); // Creates a runnable object Thread MyThread = new Thread (MyWork); // Creates instance of Thread MyThread.start(); // start the thread ...
Defining and Creating Threads • Another way of using the Runnable interface RunnabletheInvoker = new Runnable(){ public void run() { ... // Here goes the thread's work } } ... Thread t = new Thread(theInvoker); t.start(); ...
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; } }
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); } } }
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
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
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
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.Objectclass 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() }
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
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
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
Energy Management • Consider our tracking application that needs to send GPS fixes continuously • What communication protocol is more adequate? TCP? UDP?