MobAppDev (Fall 2014): Threads, Static & Non-Static Synchronization, Concurrency & Threads

18
MobAppDev Threads, Static & Non-Stastic Synchronization, Concurrency & Threads Vladimir Kulyukin www.vkedco.blogspot.com

description

 

Transcript of MobAppDev (Fall 2014): Threads, Static & Non-Static Synchronization, Concurrency & Threads

Page 1: MobAppDev (Fall 2014): Threads, Static & Non-Static Synchronization, Concurrency & Threads

MobAppDev

Threads, Static & Non-Stastic Synchronization, Concurrency &

Threads

Vladimir Kulyukin

www.vkedco.blogspot.com

Page 2: MobAppDev (Fall 2014): Threads, Static & Non-Static Synchronization, Concurrency & Threads

Outline● Threads● Static & Non-Static Synchronization● Concurrency & Threads

Page 3: MobAppDev (Fall 2014): Threads, Static & Non-Static Synchronization, Concurrency & Threads

Threads

Page 4: MobAppDev (Fall 2014): Threads, Static & Non-Static Synchronization, Concurrency & Threads

Thread Behavior● Each thread starts and runs to completion● A thread finishes when its run() method finishes● A thread can never be re-started (calling start() more than once on

the same Thread object throws IllegalThreadStateException)● The order in which the Runnable threads get to run is JVM-specific

Page 5: MobAppDev (Fall 2014): Threads, Static & Non-Static Synchronization, Concurrency & Threads

Thread Behavior● When a Thread goes to sleep (Thread.sleep() is executed) and

wakes up, it does not start running – it becomes Runnable and may be selected to run by the JVM scheduler

● A yielding Thread (Thread.yield() is executed) yields to the Threads with the same priorities but there is no guarantee that another Thread will be chosen by the JVM scheduler – the same Thread (the one that just yielded) may be chosen to run again and again

Page 6: MobAppDev (Fall 2014): Threads, Static & Non-Static Synchronization, Concurrency & Threads

Static & Non-Static Syncrhonization

Page 7: MobAppDev (Fall 2014): Threads, Static & Non-Static Synchronization, Concurrency & Threads

When Should I Synchronize?● Any time when multiple threads are accessing and modifying the

same data● Any time when there is a race condition: multiple threads render the

data inconsistent● Race condition example: Two threads A and B manipulate the

same book database. A reads a book's price and goes to sleep. B modifies the book's price. A wakes up and orders the book on the basis of the old price.

Page 8: MobAppDev (Fall 2014): Threads, Static & Non-Static Synchronization, Concurrency & Threads

How to Synchronize in Java● Every Java Instance Object and Java Class Object has a

built-in lock● Non-static methods should synchronize on Instance Objects

(this Object)● Static methods should synchronize on Class Objects● Since there is only one lock per Object, once a Thread picks

up the lock, no other thread can enter until the first Thread finishes

Page 9: MobAppDev (Fall 2014): Threads, Static & Non-Static Synchronization, Concurrency & Threads

How to Synchronize: Blocks & Methods

// Here is an example of a synchronized block

class MySync {

public void myMethod() {

synchronized(this) {

// do some stuff here

}

}

}

// Here is an example of a synchronized method

class MySync {

public void synchronized myMethod() {

// do some stuff here

}

}

Page 10: MobAppDev (Fall 2014): Threads, Static & Non-Static Synchronization, Concurrency & Threads

How to Synchronize: Static Blocks & Methods

// example of a synchronized static block

class MyStaticSync {

static int mInt = 0;

public static int getInt() {

synchronized(MyStaticSync.class) {

return mInt;

}

}

}

// Example of a synchronized static method

class MyStaticSync {

static int mInt = 0;

public static synchronized int getInt() {return mInt;

}

}

Page 11: MobAppDev (Fall 2014): Threads, Static & Non-Static Synchronization, Concurrency & Threads

How Threads Sync● Threads calling non-static synchronized methods/blocks block each

other if they synchronize on the same Instance Objects● Threads calling static synchronized methods/blocks block each other

if they synchronize on the same Class Objects● Threads executing static and non-static methods/blocks NEVER

block each other● Rule of Thumb: Be careful when mixing static and non-static

synchronization and check which Thread synchronizes on which object

Page 12: MobAppDev (Fall 2014): Threads, Static & Non-Static Synchronization, Concurrency & Threads

Concurrency & Threads

Page 13: MobAppDev (Fall 2014): Threads, Static & Non-Static Synchronization, Concurrency & Threads

Concurrent vs. Parallel

● The term concurrent typically means that processes and threads share the same CPU (or a limited number of CPUs)

● The term parallel typically means that processes and threads run on different CPUs

● Concurrent processes and threads simulate parallelism

Page 14: MobAppDev (Fall 2014): Threads, Static & Non-Static Synchronization, Concurrency & Threads

Concurrency in Java

● Concurrency in Java is realized via Threads● When it comes to concurrency in Java , the basic rule to

remember is that the order in which threads execute is never guaranteed

● The actual order of thread execution depends on the specific JVM scheduler and on the priorities of other concurrent threads

Page 15: MobAppDev (Fall 2014): Threads, Static & Non-Static Synchronization, Concurrency & Threads

Joining Threads

● Thread.join() is the method that allows one thread to wait until another thread completes

● th.join(): the current thread waits until thread th completes

● th.join(int wait_time): wait_time specifies the waiting period (in milliseconds) for the current thread

Page 16: MobAppDev (Fall 2014): Threads, Static & Non-Static Synchronization, Concurrency & Threads

Exampleclass MyJob implements Runnable {

int mUpperBound = 0; long mSum = 0;

public MyJob(int upper) { mUpperBound = upper; }

@Override

public void run() {

Log.d(ThreadTesterActivity.LOGTAG, Thread.currentThread().getName() + " running");

for(int i = 1; i < mUpperBound; i++) { mSum += i; }

Log.d(ThreadTesterActivity.LOGTAG, Thread.currentThread().getName() + " done");

}

}

long getSum() { return mSum; }

}

Example

source code is in ThreadTester.java

Page 17: MobAppDev (Fall 2014): Threads, Static & Non-Static Synchronization, Concurrency & Threads

Example: Non-guaranteed Execution// Thread execution order is not guaranteed

Log.d(ThreadTesterActivity.LOGTAG, Thread.currentThread().getName() + " running");

MyJob job01 = new MyJob(100); // First Job

MyJob job02 = new MyJob(200); // Second Job

new Thread(job01, "Thread01").start(); // First Job Mounted on a Thread

new Thread(job02, "Thread02").start(); // Second Job Mounted on a Thread

Log.d(ThreadTesterActivity.LOGTAG, "job01's sum = " + job01.getSum());

Log.d(ThreadTesterActivity.LOGTAG, "job02's sum = " + job02.getSum());

source code is in ThreadTester.java

Page 18: MobAppDev (Fall 2014): Threads, Static & Non-Static Synchronization, Concurrency & Threads

Example: Ordered Execution// Thread execution order is explicitly guaranteed with joins

MyJob job01 = new MyJob(100); MyJob job02 = new MyJob(200);

Thread thread01 = new Thread(job01, "Thread01");

Thread thread02 = new Thread(job02, "Thread02");

thread01.start(); thread02.start();

try {

thread01.join(); // main thread waits until thread01 completes

thread02.join(); // main thread waits until thread02 completes

} catch (InterruptedException e) {

e.printStackTrace();

}

Log.d(ThreadTesterActivity.LOGTAG, "job01's sum = " + job01.getSum());

Log.d(ThreadTesterActivity.LOGTAG, "job02's sum = " + job02.getSum());

source code is in ThreadTester.java