Download - Other Programming Aspects
11
Other Programming Aspects
Dr. Miguel A. LabradorDepartment of Computer Science & Engineering
[email protected]://www.csee.usf.edu/~labrador
2Copyright© Dr. Miguel A. Labrador
2Copyright© Dr. Miguel A. Labrador
2
Outline
• Memory management• Concurrency• Dynamic linking • Energy management
3Copyright© Dr. Miguel A. Labrador
3Copyright© Dr. Miguel A. Labrador
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
4Copyright© Dr. Miguel A. Labrador
4Copyright© Dr. Miguel A. Labrador
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
5Copyright© Dr. Miguel A. Labrador
5Copyright© Dr. Miguel A. Labrador
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
6Copyright© Dr. Miguel A. Labrador
6Copyright© Dr. Miguel A. Labrador
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
7Copyright© Dr. Miguel A. Labrador
7Copyright© Dr. Miguel A. Labrador
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
8Copyright© Dr. Miguel A. Labrador
8Copyright© Dr. Miguel A. Labrador
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()
9Copyright© Dr. Miguel A. Labrador
9Copyright© Dr. Miguel A. Labrador
9
Thread’s State Machine
run()
Ready SuspendedRunning
sleep(), join(), yield()
Terminate()
Sleep, expired, join, yield, completeTerminated
start()
10Copyright© Dr. Miguel A. Labrador
10Copyright© 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
11Copyright© Dr. Miguel A. Labrador
11Copyright© 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 ThreadMyThread.start(); // Start the thread...
12Copyright© Dr. Miguel A. Labrador
12Copyright© 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 objectThread MyThread = new Thread (MyWork); // Creates instance of ThreadMyThread.start(); // start the thread...
13Copyright© Dr. Miguel A. Labrador
13Copyright© 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();...
14Copyright© Dr. Miguel A. Labrador
14Copyright© 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; }}
15Copyright© Dr. Miguel A. Labrador
15Copyright© 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); } } }
16Copyright© Dr. Miguel A. Labrador
16Copyright© 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
17Copyright© Dr. Miguel A. Labrador
17Copyright© 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
18Copyright© Dr. Miguel A. Labrador
18Copyright© 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
19Copyright© Dr. Miguel A. Labrador
19Copyright© 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()}
20Copyright© Dr. Miguel A. Labrador
20Copyright© 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
21Copyright© Dr. Miguel A. Labrador
21Copyright© 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
22Copyright© Dr. Miguel A. Labrador
22Copyright© 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
23Copyright© Dr. Miguel A. Labrador
23Copyright© 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?