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:
-
Thread 1is executingreturn new Product(context);and created a new Product instance. -
Thread 2is executingthis.mContext = context;. -
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