lundi 21 janvier 2019

Android multi-thread test framework

I need to write multi-thread test for this builder pattern code. I want to ensure when I called builder from two thread, it never creates two different instance.

Suppose in two different threads, I call new Product.Builder(), without synchronized in Builder(). It is possible:

  1. Thread 1 is executing return new Product(context);and created a new Product instance.

  2. Thread 2 is executing this.mContext = context;.

  3. On next frame, thread 2 will also execute return new Product(context); and override the Product instance.

I want to write test for it in case someone removes synchronized keyword. But with JUnit, I cannot guarantee the execution order. Is there a good framework so that I can write reproducible test for multi-thread code?

public class Product  {

    private static volatile Product singleton;

    private Context mContext;


    public Product(Context context) {
        mContext = context;

    }

    public static class Builder {
        private Context mContext;
        private final Object BUILD_MONITOR = new Object();

        public Builder(){

        }

        public Product build(Context context)
        {
            synchronized (BUILD_MONITOR) {
                if (singleton != null) {
                    Logger.w("There is already an Oben TTS instance, please call release before creating new one");
                    return singleton;
                }
                this.mContext = context;
                return new Product(context);
            }
        }

    }

}

Aucun commentaire:

Enregistrer un commentaire