MobAppDev: Concurrency, Threading, & Access Synchronization

648 views
583 views

Published on

1) Concurrency
2) Threading
3) Access Synchronization

Published in: Software, Education
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
648
On SlideShare
0
From Embeds
0
Number of Embeds
44
Actions
Shares
0
Downloads
0
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

MobAppDev: Concurrency, Threading, & Access Synchronization

  1. 1. MobAppDev Concurrency, Threading, & Access Synchronization Vladimir Kulyukin www.vkedco.blogspot.com
  2. 2. Outline ● ● ● Threads Concurrency & Ordered Thread Execution Access Synchronization
  3. 3. Threads
  4. 4. 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
  5. 5. 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 yield) may be chosen to run again and again
  6. 6. 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 of the same priority will be chosen by the JVM scheduler – the same Thread (the one that just yielded) may be chosen to run again and again
  7. 7. When to 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.
  8. 8. How to Synchronize ● ● ● ● 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 pick up the lock, no other thread can enter until the first Thread finishes
  9. 9. How to Synchronize: Blocks & Methods // Here is an example of a synchronized block // Here is an example of a synchronized method class MySync { class MySync { public void synchronized myMethod() { public void myMethod() { // do some stuff here synchronized(this) { } // do some stuff here } } } }
  10. 10. How to Synchronize: Static Blocks & Methods // An example of a synchronized static block // Example of a synchronized static method class MyStaticSync { class MyStaticSync { static int mInt = 0; static int mInt = 0; public static int getInt() { public static synchronized int getInt() { return mInt; synchronized(MyStaticSync.class) { return mInt; } } } } }
  11. 11. 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
  12. 12. Concurrency & Threads
  13. 13. 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
  14. 14. 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
  15. 15. 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
  16. 16. Example class 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; } } source code is in ThreadTester.java
  17. 17. 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
  18. 18. 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
  19. 19. Access Synchronization
  20. 20. Access Synchronization ● ● Wherever there are concurrent threads that can access and modify the same objects or other resources, such as SQLite databases, questions of access synchronization must be addressed If access is not synchronized or synchronized incorrectly, objects and/or data may become inconsistent
  21. 21. Basic Rule of Thumb ● ● ● If several threads access the same object/data resource and modify it, synchronize the object/resource Shared dynamic objects must be synchronized dynamically Shared static objects must be synchronized statically
  22. 22. Example Write an application that starts four concurrent threads. Each thread moves a small circle on the canvas. Threads synchronize access to the canvas. source code is in DancingCirclesApp repo
  23. 23. Screenshot
  24. 24. Application Details: Synchronized Threads ● ● ● ● ● The application creates four circle objects on a custom view's ( PainterView.java) canvas and uses four threads to randomly move four circles on the canvas The main activity (DancingCirclesAct.java ) defines an options menu with two items: Synch Threads and Unsynch Threads When the user presses Synch Threads, the activity starts four worker threads with Runnables that synchronization the PainterView object in DancingCirclesApp.java The configuration of the circles on the canvas of the PainterView changes one circle at a time One circle thread may usurp the CPU cycles so that only one circle will be moved for a time
  25. 25. Application Details: Unsynchronized Threads ● ● When the user selects Unsynch Threads, the activity starts four worker threads with Runnables that do not synchronize on the PainterView object in DancingCirclesApp Thus, the configuration of the circles on the canvas of the PainterView changes four circles at a time

×