1 A Framework for Testing Concurrent Programs PhD Proposal Mathias Ricken Rice University December 2, 2010.

Slides:



Advertisements
Similar presentations
A Randomized Dynamic Program Analysis for Detecting Real Deadlocks Koushik Sen CS 265.
Advertisements

Concurrency 101 Shared state. Part 1: General Concepts 2.
An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.
Silberschatz, Galvin and Gagne ©2009Operating System Concepts – 8 th Edition Chapter 4: Threads.
/ PSWLAB Concurrent Bug Patterns and How to Test Them by Eitan Farchi, Yarden Nir, Shmuel Ur published in the proceedings of IPDPS’03 (PADTAD2003)
ConcJUnit: Unit Testing for Concurrent Programs PPPJ 2009 Mathias Ricken and Robert Cartwright Rice University August 28, 2009.
Java How to Program, 9/e CET 3640 Professor: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Atomicity in Multi-Threaded Programs Prachi Tiwari University of California, Santa Cruz CMPS 203 Programming Languages, Fall 2004.
Intro to Threading CS221 – 4/20/09. What we’ll cover today Finish the DOTS program Introduction to threads and multi-threading.
Threading Part 2 CS221 – 4/22/09. Where We Left Off Simple Threads Program: – Start a worker thread from the Main thread – Worker thread prints messages.
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.
Java How to Program, 9/e CET 3640 Professor: Dr. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Multithreading.
50.003: Elements of Software Construction Week 5 Basics of Threads.
Testing Concurrent Programs COMP Production Programming Mathias Ricken Rice University Spring 2009.
Unit Testing in Java with an Emphasis on Concurrency Corky Cartwright Rice and Halmstad Universities Summer 2013.
1 Advanced Computer Programming Concurrency Multithreaded Programs Copyright © Texas Education Agency, 2013.
1 Lecture 4: Threads Operating System Fall Contents Overview: Processes & Threads Benefits of Threads Thread State and Operations User Thread.
Java Programming: Advanced Topics
Object Oriented Programming Lecture 8: Introduction to laboratorial exercise – part II, Introduction to GUI frames in Netbeans, Introduction to threads.
Threads in Java. History  Process is a program in execution  Has stack/heap memory  Has a program counter  Multiuser operating systems since the sixties.
Threading and Concurrency Issues ● Creating Threads ● In Java ● Subclassing Thread ● Implementing Runnable ● Synchronization ● Immutable ● Synchronized.
Test-First Java Concurrency for the Classroom SIGCSE 2010 Mathias Ricken and Robert Cartwright Rice University March 12, 2009.
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.
Threads Concurrency in Java. What is mult-tasking? Doing more than one task.
111 © 2002, Cisco Systems, Inc. All rights reserved.
Practical OOP using Java Basis Faqueer Tanvir Ahmed, 08 Jan 2012.
Java Threads. What is a Thread? A thread can be loosely defined as a separate stream of execution that takes place simultaneously with and independently.
Threads in Java. Processes and Threads Processes –A process has a self-contained execution environment. –Has complete set of runtime resources including.
Testing Concurrent Programs, A 7-Minute Jargon-Free Introduction Thesis Writing Seminar Mathias Ricken Rice University February 25, 2010.
CS 346 – Chapter 4 Threads –How they differ from processes –Definition, purpose Threads of the same process share: code, data, open files –Types –Support.
1 A Framework for Testing Concurrent Programs PhD Thesis Defense Mathias Ricken Rice University January 10, 2011.
COMP 111 Threads and concurrency Sept 28, Tufts University Computer Science2 Who is this guy? I am not Prof. Couch Obvious? Sam Guyer New assistant.
Operating Systems ECE344 Ashvin Goel ECE University of Toronto Mutual Exclusion.
A Framework for Testing Concurrent Programs COMP 600 Mathias Ricken Rice University August 27, 2007.
A Framework for Testing Concurrent Programs MS Thesis Defense Mathias Ricken Rice University June 14, 2007.
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
ICS 313: Programming Language Theory Chapter 13: Concurrency.
Concurrency in Java Brad Vander Zanden. Processes and Threads Process: A self-contained execution environment Thread: Exists within a process and shares.
Introduction to Threads Session 01 Java Simplified / Session 14 / 2 of 28 Objectives Define a thread Define multithreading List benefits of multithreading.
Java Thread and Memory Model
Concurrency Control 1 Fall 2014 CS7020: Game Design and Development.
Threads in Java1 Concurrency Synchronizing threads, thread pools, etc.
Multithreaded programming  Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run.
Parallel Processing (CS526) Spring 2012(Week 8).  Shared Memory Architecture  Shared Memory Programming & PLs  Java Threads  Preparing the Environment.
13-1 Chapter 13 Concurrency Topics Introduction Introduction to Subprogram-Level Concurrency Semaphores Monitors Message Passing Java Threads C# Threads.
Polytechnic University of Tirana Faculty of Information Technology Computer Engineering Department A MULTITHREADED SEARCH ENGINE AND TESTING OF MULTITHREADED.
ConcJUnit: Unit Testing for Concurrent Programs COMP 600 Mathias Ricken Rice University August 24, 2009.
Multithreading. Multitasking The multitasking is the ability of single processor to perform more than one operation at the same time Once systems allowed.
© Andy Wellings, 2004 Thread Priorities I  Although priorities can be given to Java threads, they are only used as a guide to the underlying scheduler.
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.
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
A brief intro to: Parallelism, Threads, and Concurrency
Java Programming Language
Multithreaded Programming in Java
Multithreading.
Multithreaded Programming
Threads Chapter 4.
Dr. Mustafa Cem Kasapbaşı
21 Threads.
Java Concurrency.
Java Concurrency.
Testing Concurrent Programs
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

1 A Framework for Testing Concurrent Programs PhD Proposal Mathias Ricken Rice University December 2, 2010

2 Brian Goetz, Java Concurrency in Practice, Addison-Wesley, 2006 Concurrency in Practice

3 Concurrency Practiced Badly Concurrent programming is difficult and not well supported by today’s tools. This framework simplifies the task of developing and debugging concurrent programs.

4 Contributions 1.Improved JUnit Framework 2.Execution with Random Delays 3.Program Restrictions to Simplify Testing 4.Additional Tools for Testing a.Invariant Checker b.Execution Logger 5.Miscellaneous

5 Unit Tests… Occur early Automate testing Keep the shared repository clean Serve as documentation Prevent bugs from reoccurring Allow safe refactoring Unfortunately not effective with multiple threads of control

6 Improvements to JUnit

7 Existing Testing Frameworks JUnit, TestNG Don’t detect test failures in child threads Don’t ensure that child threads terminate Tests that should fail may succeed

8 ConcJUnit Replacement for JUnit –Backward compatible, just replace junit.jar file 1.Detects failures in all threads 2.Warns if child threads or tasks in the event thread outlive main thread 3.Warns if child threads are not joined MS PhD

9 Both tests fail. Sample JUnit Tests public class Test extends TestCase { public void testException() { throw new RuntimeException("booh!"); } public void testAssertion() { assertEquals(0, 1); } } if (0!=1) throw new AssertionFailedError(); } Both tests fail.

10 JUnit Test with Child Thread public class Test extends TestCase { public void testException() { new Thread() { public void run() { throw new RuntimeException("booh!"); } }.start(); } new Thread() { public void run() { throw new RuntimeException("booh!"); } }.start(); throw new RuntimeException("booh!"); Main thread Child thread Main thread Child thread spawns uncaught! end of test success!

11 Changes to JUnit Check for living child threads after test ends Reasoning: Uncaught exceptions in all threads must cause failure If the test is declared a success before all child threads have ended, failures may go unnoticed Therefore, all child threads must terminate before test ends

12 Check for Living Threads public class Test extends TestCase { public void testException() { new Thread() { public void run() { throw new RuntimeException("booh!"); } }.start(); } new Thread() { public void run() { throw new RuntimeException("booh!"); } }.start(); throw new RuntimeException("booh!"); Test thread Child thread uncaught ! end of test failure! invokes group’s handler Main thread check for living child threads check group’s handler

13 Changes to JUnit (2) Check if any child threads were not joined Reasoning: All child threads must terminate before test ends Without join() operation, a test may get “lucky” Require all child threads to be joined

14 Fork/Join Model Parent thread joins with each of its child threads May be too limited for a general-purpose programming language Child thread 1 Child thread 2 Main thread

15 Other Join Model Examples Chain of child threads guaranteed to outlive parent Main thread joins with last thread of chain Child thread 1 Child thread 2 Main thread Child thread 3

16 Generalize to Join Graph Threads as nodes; edges to joined thread Test is well-formed as long as all threads are reachable from main thread Child thread 1 Child thread 2 Main thread Child thread 3 MT CT1 CT2 CT3

17 Child thread 1 Child thread 2 Main thread MT CT1 CT2 Unreachable Nodes An unreachable node has not been joined –Child thread may outlive the test

18 ConcJUnit Evaluation JFreeChart –All tests passed; tests are not concurrent DrJava: 900 unit tests –Passed:880 –No join: 1 –Lucky: 18 –Timeout: 1 –Runtime overhead: ~1 percent

19 ConcJUnit Limitations Only checks chosen schedule –A different schedule may still fail Example: Thread t = new Thread(…); if (nondeterministic()) t.join(); *2

20 Execution with Random Delays

21 Why Is This Necessary? Nondeterminism –Tests may execute under different schedules, yielding different results –Example: nondeterministic join (see above) –Example: data race (multithreaded counter) int counter = 0; // in M threads concurrently for(int i=0; i<N; ++i) { ++counter; } // after join: counter == M*N?

22 Race-Free ≠ Deterministic Race-free programs can still be nondeterministic final Object lock = new Object(); final Queue q = new ArrayList(); // in one thread... synchronized(lock) { q.add(0); }... // in other thread... synchronized(lock) { q.add(1); }... // after join: q = (0, 1) or (1, 0)?

23 Nondeterminism = Error? Depends on the computation –If the queue (see previous example) was to contain {0, 1} in any order, then no error –If the queue was to contain (0, 1) in order, then error A unit test should be deterministic (with respect to thread scheduling) –Schedule should be considered an input parameter Run test under all possible schedules? *3

24 Intractability Comprehensive testing is intractable Number of schedules (N) –t: # of threads, s: # of slices per thread Can we still find many of the problems? *4

25 Previous Work: ConTest ConTest (Edelstein 2002) Programs seeded with calls to sleep, yield, or priority methods at synchronization events At runtime, random or coverage-based decision to execute seeded instructions sleep performed best Problem: predates Java Memory Model (JMM), does not treat volatile fields correctly

26 Previous Work: rsTest rsTest (Stoller 2002) Similar to ConTest, but fewer seeds –Better classification of shared objects “Probabilistic completeness” –Non-zero probability rsTest will exhibit a defect, even if the scheduler on the test system normally prohibits it from occurring Problem: also predates the JMM, does not treat volatile fields correctly

27 Goal for Concutest Execution with random delays –Similar to ConTest –Cover all events relevant to synchronization, as specified by the JMM, i.e. particularly volatile fields

28 Synchronization Points Thread.start (before) Thread.exit (after) Thread.join (before and after) Object.notify/notifyAll (before) Object.wait (before and after) MONITORENTER (before) MONITOREXIT (before) Synchronized methods changed to blocks Access to volatile fields (before)

29 Examples Multithreaded counter –If counter is volatile Multithreaded queue Early notify Missing wait - notify synchronization (assume another thread completed) Need more examples

30 Benchmarks Still to do

31 Program Restrictions to Simplify Testing

32 ConcJUnit Child threads must be joined –Only way to ensure that all errors are detected Slight inconvenience –Keep track of child threads when they are created ConcJUnit provides utilities for this

33 Shared Variables Shared variables must be either –consistently protected by a lock, or –volatile, or –final This can be checked using a race detector (e.g. Chord, Naik 2006; FastTrack, Flanagan 2009)

34 Volatile Variables Specify which volatile variables should be instrumented with random delays a.Manually (e.g. “in all user classes” or “in classes in package xyz”) b.Use static “may happen in parallel” (MHP) analysis (e.g. Soot MHP, Li 2005)

35 Additional Tools for Testing

36 Additional Tools for Testing 1.Annotations for Invariant Checking Runtime warning if invariants for a method are not maintained Annotations now support subtyping 2.Annotations for Execution Logging MS PhD

37 Additional Tools for Testing: Annotations for Invariant Checking

38 Concurrency Invariants Methods have to be called in event thread –TableModel, TreeModel Method may not be called in event thread –invokeAndWait() Must acquire readers/writers lock before methods are called –AbstractDocument –DrJava’s documents Invariants difficult to determine

39 Invariant Annotations Add invariants as public static void invokeAndWait(Runnable r) {... } Process class files –Find uses of annotations –Insert code to check invariants at method beginning

40 Advantages of Annotations Java language constructs –Syntax checked by compiler Easy to apply to part of the program –e.g. when compared to a type system change Light-weight –Negligible runtime impact if not debugging (only slightly bigger class files) –<1% when debugging Automatic Checking

41 Limitations of Java Annotations Java does not allow the same annotation class to occur // error void testMethod() { … } Conjunctions, disjunctions and negations?

42 Subtyping for Annotations Let annotation extend a supertype? Invariant { } OnlyThreadWithName extends Invariant { String name(); } And extends Invariant { Invariant[] terms(); } Subtyping not allowed for annotations –Extended Annotations Java Compiler (xajavac)

43 Invariant etc. Subtyping reduced implementation size by a factor of 3 while making invariants more expressive

44 Additional Tools for Testing: Annotations for Execution Logging

45 Need for Execution Logging Tests need to check if code was executed Implementation options when no variable can be checked –Add flag to application code –Add flag to test code, add call from application code to test code Application and test code become tightly coupled

46 Logging Annotations Annotate test with methods that need to be logged m="bar")) void testMethod() { … } Process class files –Find methods mentioned in annotations –Insert code to increment counter at method beginning

47 Logging Annotations (2) Decouples application code from test Annotations with subtyping useful for logging m="bar", })) void testMethod() { … }

48 Log Benchmarks Setup Different implementations –Naïve –Non-blocking –Per-thread –Fields –Local fields Different numbers of threads (1-16)

49 Log Benchmarks Setup (2) Three different benchmarks –Tight loop –Outer loop –DrJava subclasses of GlobalModelTestCase Expressed as factor of execution time with hand-written logging or no logging –1.0 = no change

50 Execution Log Benchmarks

51 Execution Log Benchmarks

52 Log Benchmark Results “Local fields” performs best Compared to hand-written logging –No slowdown Compared to no logging –10% to 50% slowdown in tight loop –~1% slowdown in outer loop –No measurable slowdown in DrJava

53 Summary

54 Summary 1.Improved JUnit Framework Detects errors in all threads Warns if child threads are still alive and errors could be missed Warns if child threads ended on time, but not because they were joined Low overhead (~1%)  Much more robust unit tests

55 Summary (2) 2.Execution with Random Delays Detects many types of concurrency defects Updated for the Java Memory Model (JMM)  Higher probability of finding defects usually obscured by scheduler

56 Summary (3) 3.Program Restrictions to Simplify Testing Child threads in tests must be joined Shared variables must be consistently locked, volatile, or final Volatile variables to be instrumented must be listed  Restrictions are not prohibitive

57 Summary (4) 4.Additional Tools for Testing Invariant Checker encodes and checks method invariants Execution Logger decouples tests and application code Low overhead (~1%)  Simpler to write good tests

58 Summary (5) 5.Miscellaneous Subtyping for annotations useful, compatible with existing Java DrJava integration makes better tools available to beginners This framework simplifies the task of developing and debugging concurrent programs.

59 Still To Do Execution with random delays –More examples –Benchmark –Evaluate choice of delay lengths Write, write, write

60 Acknowledgements I thank the following people for their support. My advisor –Corky Cartwright My committee members –Walid Taha –David Scott –Bill Scherer (MS) NSF, Texas ATP, Rice School of Engineering –For providing partial funding

61 Notes

62 public class Test extends TestCase { public void testException() { Thread t = new Thread(new Runnable() { public void run() { throw new RuntimeException("booh!"); } }); t.start(); while(t.isAlive()) { try { t.join(); } catch(InterruptedException ie) { } } Thread t = new Thread(new Runnable() { public void run() { throw new RuntimeException("booh!"); } }); t.start(); while(t.isAlive()) { try { t.join(); } catch(InterruptedException ie) { } } throw new RuntimeException("booh!"); Loop since join() may end spuriously Notes (1) 1.Only add edge if joined thread is really dead; do not add if join ended spuriously. ←←

63 Notes (2) 2.Also cannot detect uncaught exceptions in a program’s uncaught exception handler (JLS limitation) ←← 3.There are exceptions when a test may not have to be deterministic, but it should be probabilistic. Example: Data for some model is generated using a random number generator. ←←

64 Notes (3) 3.Number of schedules, derived ←← Product of s-combinations: For thread 1: choose s out of ts time slices For thread 2: choose s out of ts-s time slices … For thread t-1: choose s out of 2s time slices For thread t-1: choose s out of s time slices Writing s-combinations using factorial Cancel out terms in denominator and next numerator Left with (ts)! in numerator and t numerators with s!

65 Image Attribution 1.Image on Concurrency in Practice: Adapted from Brian Goetz et al. 2006, Addison WesleyConcurrency in PracticeBrian Goetz et al. 2006, Addison Wesley 2.Image on Concurrency Practiced Badly: Caption FridaysConcurrency Practiced Badly Caption Fridays