Test of Java concurrency programming

Source: Internet
Author: User

Key points of concurrent program testing
    • Throughput
    • Responsiveness of
    • Scalability
Correctness Test

First, you need a test-ready program for chestnuts. That's the one below. A fixed-length queue that defines a blocking put and take method and controls it with two counters.

Import Java.util.concurrent.semaphore;public class Boundedbuffer<e> {Private final Semaphore availableitems, Availablespaces;private final e[] items;private int putposition = 0, takeposition = 0;public boundedbuffer (int capacity) { Availableitems = new Semaphore (0), availablespaces = new Semaphore (capacity); Items = (e[]) new object[capacity];} public Boolean isEmpty () {return availableitems.availablepermits () = = 0;} public Boolean isfull () {return availablespaces.availablepermits () = = 0;} public void put (E x) throws Interruptedexception {Availablespaces.acquire ();d oinsert (x); Availableitems.release ();} Public E take () throws Interruptedexception {Availableitems.acquire (); E item = Doextra (); Availablespaces.release (); return item;} Private synchronized void Doinsert (E x) {//TODO auto-generated method Stubint i = putposition;items[i] = X;putposition = (++i = = items.length)? 0:I;} Private synchronized E Doextra () {int i = takeposition; E x = items[i];items[i] = Null;takeposition = (++i = = Items.length)? 0:i;return x;}}

Basic unit Testing

You can use JUnit.

Import static Org.junit.assert.*;import Org.junit.test;public class Boundedbuffertest {@Testpublic void Test () { Testisemptywhenconstructed (); try {testisfullafterputs ();} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}} void testisemptywhenconstructed () {boundedbuffer<integer> bb = new boundedbuffer<integer> (ten); assertTrue (Bb.isempty ()); Assertfalse (Bb.isfull ());} void Testisfullafterputs () throws interruptedexception {boundedbuffer<integer> bb = new Boundedbuffer<integer > (int i = 0; i < ten; i++) {bb.put (i);} Assertfalse (Bb.isempty ()); Asserttrue (Bb.isfull ());}}

The main test is the boundary condition.

testing for blocking operations

The test code tries to take an element from the empty cache, and if it succeeds then the test fails. Then wait a while before interrupting the thread. If the fetch thread is properly blocked in take, then Interruptedexception will be thrown. The catch block that catches the exception tries to test successfully and let the thread exit, and then the main test thread attempts to merge with the get thread to verify that the Join method returns successfully by calling the IsAlive method. If the fetch thread can break threads, then the join can be completed very quickly.

void Testtakeblockswhenempty () {final boundedbuffer<integer> bb = new boundedbuffer<integer> (10); Thread taker = new Thread () {@Overridepublic void Run () {//TODO auto-generated method stubtry {int unused = Bb.take (); FAI L ();} catch (Interruptedexception success) {}}};try {taker.start (); Thread.Sleep (lockup_detect_timeout); Taker.interrupt (); Taker.join (lockup_detect_timeout); AssertFalse ( Taker.isalive ());} catch (Exception unexception) {fail ();}}

Security testing

Tests whether an error occurs under a data race condition. This requires a concurrent test program. It may be more difficult than writing the class itself to test.

A sequence-sensitive checksum calculation function is performed to calculate and compare the elements of all into row, as well as the test and comparison of the dequeue elements. If they are equal, then the test is successful. If there is only one producer and one consumer, then this method can play the most role. Because it is not only able to test whether the correct element is removed, but also to test whether the order of the elements are taken out is correct,

If you want to extend this approach to multi-producer and multi-consumer situations, you need a checksum function that is insensitive to the into row and dequeue order of the elements. Thus, after the test program runs, multiple tests can be combined in different order, and if not, multiple threads need to access the same shared test and variable, so synchronization is required, which becomes a concurrency bottleneck.

To ensure that the test program can correctly test all the points, it must not allow the compiler to pre-guess the values of the test and. It will have an impact on many other tests. Because most random class generators are thread-safe. and will bring additional synchronization overhead. So it's better to use a simple pseudo-random function.

static int xorshift (int y) {y ^= (y << 6), y ^= (y >>> x), y ^= (y << 7), return y;}

Parameters with Nanotime (); I think using the pseudo-random number above might be a bit of a time delay, because Nanotime is the time to get the nanosecond level. After a few minutes of operation, the data generated will inevitably be different. So it basically achieves the need to get different data.

Import Java.util.concurrent.cyclicbarrier;import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;import java.util.concurrent.atomic.atomicinteger;import static org.junit.Assert.*; Import Org.junit.test;public class Puttaketest {private static final executorservice pool = Executors.newcachedthreadpool ();p rivate final Atomicinteger putsum = new Atomicinteger (0);p rivate final Atomicinteger Takesum = new Atomicinteger (0);p rivate final cyclicbarrier barrier;private final boundedbuffer<integer> BB; Private final int ntrials, npairs;public puttaketest (int capacity, int ntrials, int npairs) {this.bb = new BOUNDEDBUFFER&L T;integer> (capacity); Ntrials = Ntrials;this.npairs = Npairs;this.barrier = new Cyclicbarrier (Npairs * 2 + 1);} public static void Main (string[] args) {new Puttaketest (ten, 100000, ten). Test ();p Ool.shutdown (); void Test () {try {for (int i = 0; i < npairs; i++) {Pool.execute (New Producer ());p Ool.execute (New Consumer ());} Barrier.await (); Barrier.awAIT (); Assertequals (Putsum.get (), Takesum.get ());} catch (Exception e) {//Todo:handle Exceptionthrow new RuntimeException (e);}} Class Producer implements Runnable {@Overridepublic void Run () {//TODO auto-generated method stubtry {int seed = (this.ha Shcode () ^ (int) system.nanotime ()); int sum = 0;barrier.await (); for (int i = ntrials; i > 0; i--) {bb.put (seed); sum + = Seed;seed = Xorshift (seed);} Putsum.getandadd (sum); barrier.await ();} catch (Exception e) {//Todo:handle Exceptionthrow new RuntimeException (e);}}  Class Consumer implements Runnable {@Overridepublic void Run () {//TODO auto-generated method stubtry {barrier.await (); int sum = 0;for (int i = ntrials; i > 0; i--) {sum + = Bb.take ();} Takesum.getandadd (sum); barrier.await ();} catch (Exception e) {//Todo:handle Exceptionthrow new RuntimeException (e);}} static int xorshift (int y) {y ^= (y << 6), y ^= (y >>> x), y ^= (y << 7); return y;}}

This test should be run on a multiprocessor system. To maximize the program detection of some time-sensitive data competition, then the number of threads in the test should be more than the number of CPUs, so that at any given moment some threads are running, and others are swapped out, so that you can check the predictability of the alternating behavior of threads.








Test of Java concurrency programming

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.