I have developed a solution for Readers-Writers problem using thread.
I have one monitor class and one Reader and one Writer class.Reader and writer class extend thread.
Now I am testing the code like this:
public static void main(String[] args) {
ReadersWriters controller = new ReadersWriters();
Reader r0=new Reader(controller);
Reader r1=new Reader(controller);
Reader r2=new Reader(controller);
Reader r3=new Reader(controller);
Writer w0=new Writer(controller);
Writer w1=new Writer(controller);
Writer w2=new Writer(controller);
Writer w3=new Writer(controller);
r0.run();
w0.run();
r2.run();
r3.run();
r1.run();
r3.run();
r2.run();
w2.run();
r1.run();
w1.run();
w3.run();
}
And the output which I am getting is this:
Reader number 0 arrives
Reader number 0 starts to read
Reader number 0 finishes reading
Writer number 0 arrives
Writer number 0 starts to write
Writer number 0 finishes writing
Reader number 2 arrives
Reader number 2 starts to read
Reader number 2 finishes reading
…and so on.
The problem here is that I am unable to test the concurrency.Because it looks like my main program is calling Reader or writer one by one,which is not the kind of testing I am trying to achieve.
Can anyone help me please.Please feel free to ask any clarification you might need.
It looks like you’ve implemented a
Runnable, but not wrapped it in a thread. I suspect you’re callingrun()on yourRunnable, rather thanstart()on a thread. Check the tutorial section on defining/starting a thread.You can’t reliably test multi-threaded code in unit tests and the like. It could work one time, or many times, and only fail once in a million test cases (or immediately in production). I would favour thread-safe coding techniques (e.g. writing immutable objects), static code analysis tools (e.g. PMD), and perhaps code reviews if you’re unsure.