Writing a test harness for a class - java

I have made a Selector concrete class with the code implementation placed inside it, the class extends from an abstract class and implements abstract methods.
public class Selector extends ASelector {
int max;
int min;
#Override
public void selectorRange(int min, int max) {
this.min = min;
this.max = max;
}
#Override
public int selectorValue() {
Random r = new Random();
int randomNumber = r.nextInt(this.max - this.min) + min;
return randomNumber;
}
}
I have been asked to write a test harness to ensure the class is working. There is a template laid out like so:
public void run() {
StdOut.println("DSA Coursework started\n");
doPart1();
doPart2();
doPart3();
doPart4();
doPart5();
StdOut.println("\nDSA Coursework completed");
}
private void doPart1() {
StdOut.println("Part1 started\n");
// Write test harness here
StdOut.println("\nPart1 completed");
StdOut.println("==============================================\n");
}
I'm unsure as to how I would go about testing the class. What code do I need to write?

I would assume you are supposed to test that the only method your class has returns the expected result? So you could start by doing something like this:
// Write test harness here
int min = 1;
int max = 10;
Selector selector = new Selector(min, max);
assert selector.selectorValue() >= min && selector.selectorValue() < max

Related

Array sum ForkJoin implementation slower than the serial implementation

So I am trying to understand how Java ForkJoin framework works. The simplest thing I could think of implementing was an array sum. However my parallel implementation is 3-4 times slower than the serial implementation. I must obviously be doing something wrong, but I am not sure what.
To measure the performance, I created a set of classes and interfaces (I used Lombok annotations for generating boilerplate code).
interface Result<T> {
T getValue();
}
#AllArgsConstructor(staticName = "of")
#Value
class MeasuredResult<T> implements Result<T> {
T value;
long elapsedTimeMillis;
}
#AllArgsConstructor(staticName = "of")
class CombinedResult<T> implements Result<T> {
private final MeasuredResult<T> parallelResult;
private final MeasuredResult<T> serialResult;
public double getParallelizationFactor() {
return (double) serialResult.getElapsedTimeMillis() / parallelResult.getElapsedTimeMillis();
}
public T getParallelValue() {
return parallelResult.getValue();
}
public T getSerialValue() {
return parallelResult.getValue();
}
#Override
public T getValue() {
return getSerialValue();
}
public boolean isDifferent() {
return !isSame();
}
public boolean isSame() {
return parallelResult.getValue().equals(serialResult.getValue());
}
}
interface Parallelizable<T> {
T processParallelly();
T processSerially();
default CombinedResult<T> getResult() {
MeasuredResult<T> parallelResult = measureParallel();
MeasuredResult<T> serialResult = measureSerial();
return CombinedResult.of(parallelResult, serialResult);
}
default MeasuredResult<T> measure(Supplier<T> supplier) {
long startTime = System.currentTimeMillis();
T value = supplier.get();
long endTime = System.currentTimeMillis();
return MeasuredResult.of(value, endTime - startTime);
}
default MeasuredResult<T> measureParallel() {
return measure(this::processParallelly);
}
default MeasuredResult<T> measureSerial() {
return measure(this::processSerially);
}
}
The idea was that by implementing the Parallelizable interface, I'd define the serial and parallel versions of the code and use the getResult() function to get a CombinedResult object with the values and time measurement to unit test with. Here's my implementation of the array sum.
#AllArgsConstructor
public class ArraySum implements Parallelizable<Integer> {
private final int[] nums;
#Override
public Integer processParallelly() {
return new ParallelForkJoinImpl(0, nums.length).compute();
}
#Override
public Integer processSerially() {
int sum = 0;
for (int num : nums) {
sum += num;
}
return sum;
}
#AllArgsConstructor()
private class ParallelForkJoinImpl extends RecursiveTask<Integer> {
private static final int THRESHOLD = 1_000;
private final int start;
private final int end;
#Override
protected Integer compute() {
if (end - start <= THRESHOLD) {
int sum = 0;
for (int i = start; i < end; i++) {
sum += nums[i];
}
return sum;
}
int mid = (start + end) / 2;
ForkJoinTask<Integer> left = new ParallelForkJoinImpl(start, mid).fork();
ForkJoinTask<Integer> right = new ParallelForkJoinImpl(mid, end).fork();
return left.join() + right.join();
}
}
}
From what I understand, calling fork() on the RecursiveTask implementation should give me a Future object as response which will block on computation when the join() function is called on it. Also use the common ForkJoinPool will automatically be used when fork() is called.
But like I said, the value for elapsedTimeMillis for the parallel implementation is 3-4 times larger than the serial implementation, and I don't know why. What did I do wrong here?

Inheritance var java

this is the qa:
Define a class called MoreSpeed which extends the following class, and which provides a new method called incSpeed() which adds 1 to the inherited variable length.
this is my answer:
public class Speed {
private int length = 0;
public int getSpeed () { return length; }
public void setSpeed (int i) {
if (i > 0) {
length = i;
}
}
}
public class MoreSpeed extends Speed {
private int length;
public int incSpeed() {
return length+1;
}}
its says that the syntax is good but the class operation is wrong.
please help me,thanks.
No. You are shadowing the length from Speed. Instead, implement incSpeed with getSpeed() like
public int incSpeed() {
return getSpeed() + 1;
}
If you are supposed to modify it as well then use setSpeed(int) to do so
public int incSpeed() {
int s = getSpeed() + 1;
setSpeed(s);
return s;
}

array initialized in one class but contents not accessible in another

i have a javafx application and it has two classes in it, namely "Client" and "Interface_Client_Impl". i have defined an int array in "Client" class and a function that initializes that array. when i tried to access the array contents at index i from Interface_Client_Impl, it always returns 0. Interface_Client_Impl class is accessed remotely and im able to get the values of variables but not the array. where am i going wrong. -_-
this is what i have.
public class Client extends Application
{
public int size = 4;
public int array[] = new int[size];
public int min = 1;
public int max = 99;
public static void main(String[] args) throws Exception
{
launch(args);
}
#Override
public void start(Stage primaryStage) throws NotBoundException, RemoteException
{
initialize_arr();
//other codes
}
public void initialize_arr()
{
Random rand = new Random();
for(int i = 0; i < size; i++)
{//initialize with random values
int val = rand.nextInt(max - min + 1) + min;
array[i] = val;
}
}
}
//another class
public class Interface_Client_Impl extends UnicastRemoteObject implements Interface_Client
{
public Client client = new Client();
#Override
public int exchange(int val)
{
Random rand = new Random();
int pos = rand.nextInt(client.size);
int return_val = client.array[pos];
client.array[pos] = val;
return return_val;
}
}
You have just created the instance for Client in class Interface_Client_Impl
You need to invoke the array initialization of client instance. You can do via following two ways
By invoking public method client.start(primaryStage)
or
by invoking public method client.initialize_arr()

How to construct a method that needs to pass in the values from a constructor?

I'm writing a program that is based around registering the amount of energy consumption that is being used by appliances within a house. So far, I have created various meter classes such as WaterMeter, GasMeter etc. with empty methods that need to be filed with values, I have also created classes for appliances that have methods that will be used to register the consumption of energy within each appliance. What I am working on now is applying the energy values that are stored within a constructor, putting those values into a timePasses() method that will then return those values to their specific meter's methods so that they can be registered. This is what I have so far:
Appliance class example:
public class ElectricShower extends Shower
{
public int isOn = -1;
public int isOff = 0;
public int incrementTime;
public int x = -1;
private static ElectricMeter instance = new ElectricMeter();
public static ElectricMeter getInstance() { return instance; }
#Override
public int currentState()
{
if (x == 0)
return isOff;
else
{
return isOn;
}
//returns isOn;
}
#Override
public void useTime(int defaultTime)
{
defaultTime = 15;
incrementTime = 1;
}
public void shower()
{
//call timePasses() method
}
#Override
public int timePasses()
{
if(x == isOff)
return 0;
else
{
ElectricMeter.getInstance().incrementConsumed(electricityUse);
}
}
ElectricShower(int electricityUse, int gasUse, int waterUse, int timeOn)
{
super(electricityUse, gasUse, waterUse, timeOn);
this.electricityUse = 12 * incrementTime;
this.gasUse = 0 * incrementTime;
this.waterUse = 4 * incrementTime;
this.timeOn = 15 * incrementTime;
}
}
Meter example:
public class ElectricMeter
{
public int incrementConsumed(int value)
{
}
public int incrementGenerated()
{
}
public boolean canGenerate()
{
}
public String getConsumed()
{
}
public String getGenerated()
{
}
}
What I need to do next is:
take the values of electricityUse and waterUse and store them within the timePasses() else staement
Within the timePasses() else statement, place the value of electrcityUse in the incrementGenerated() method within the ElectricMeter class and do the same for the waterUse variable.
UPDATE
Classes have been updated, still struggling to find out how to make it work.
First of all, I assume you have an Appliance class that all the appliances extends from. You should create variables in the Appliance class that stores electricity, gas and water usage:
public class Appliance
{
public int electricityUse, gasUse, waterUse, timeOn;
// ...
}
Note that you should always use getters and setters instead of public fields. I'm just lazy :D
Change your constructor so that the variables above get set:
ElectricShower(int electricityUse, int gasUse, int waterUse, int timeOn)
{
super(electricityUse, gasUse, waterUse, timeOn);
// I don't know why you multiply the constant by incrementTime here. Seems weird. I think you can remove them.
this.electricityUse = 12 * incrementTime;
this.gasUse = 0 * incrementTime;
this.waterUse = 4 * incrementTime;
this.timeOn = 15 * incrementTime;
}
One way to write the else clause is to use the "Singleton Pattern".
In every meter class, write something like this:
private ElectricMeter() {}
private static ElectricMeter instance = new ElectricMeter();
public static ElectricMeter getInstance() { return instance; }
In the incrementConsumed method, you should accept a parameter that indicates how much to increment:
public int incrementConsumed(int value)
{
// logic here...
}
In the else clause, you can just do:
ElectricMeter.getInstance().incrementConsumed(electricityUse);
GasMeter.getInstance().incrementConsumed(gasUse);
WaterMeter.getInstance().incrementConsumed(waterUse);
You should review your design.
If you need to access to a class parameter you could just define it public or better create a so called getter method that returns the value.
Example:
public class MyData {
public int counter;
}
....
// Some other class
MyData data = new MyData();
data.counter = 5;
System.out.println(data.counter);
Or
public class MyData {
private int counter;
public void setCounter(int counter) {
this.counter = counter;
}
public int getCounter() {
return this.counter;
}
}
....
// Some other class
MyData data = new MyData();
data.setCounter(5);
System.out.println(data.getCounter());
In your code I see:
public int incrementConsumed()
{
//Store value of electricityUse.
}
But this method should just return an integer and have not parameter to get an input to store.
It should be:
public void incrementConsumed(int amount) {
this.amount += amount;
}
I'm concerned about this line:
gasUse = 0 * incrementTime;
If you multiply something to 0 it will be always 0...

JAVA: How to simulate concurrency

I have to create an application which simulates concurrent threads. The "server" creates a number of "threads" and stores them in a queue. Each "thread" has defined a time to finish his execution. The server polls each "thread" from the queue to do his job for 10 ms. If the thread has finished his job, it is removed from the queue. If not, it is added at the end of the queue. I used for this application PriorityQueue. The problem is that the code i wrote is not giving the expected output; a "thread" is executed until his execution time ends.
How can I solve this problem?
SimulatedThread class
public class SimulatedThread {
private int executionTime;
private Integer id;
private int executedTime;
private boolean finished;
public SimulatedThread(){
executedTime = 0;
executionTime = 0;
setFinished(false);
}
//getters and setters
}
Server class
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Random;
public class Server {
final int TIME = 10;
final int TH_NO = 10;
//priority
final int MIN_P = 1;
final int MAX_P = 100;
//execution time
final int MIN_E = 10;
final int MAX_E = 100;
private PriorityQueue<SimulatedThread> activeThreads;
public Server() {
Comparator<SimulatedThread> comparator = new SimulatedThreadComparator();
activeThreads = new PriorityQueue<SimulatedThread>(10,comparator);
}
public void createThreads(){
for( int i = 0; i < TH_NO; i++){
SimulatedThread th = new SimulatedThread();
th.setExecutionTime(generator(MAX_E, MIN_E));
th.setId(generator(MAX_P,MIN_P));
System.out.println("New thread has been created");
System.out.println(th.toString());
activeThreads.add(th);
}
}
public void executeThreads(){
while(!activeThreads.isEmpty()){
SimulatedThread th = activeThreads.poll();
if(!th.isFinished()){
try {
Thread.sleep(TIME);
th.setExecutedTime(th.getExecutedTime() + TIME);
System.out.println(th.toString());
if((th.getExecutionTime() - th.getExecutedTime()) <= 0 ){
th.setFinished(true);
} else{
activeThreads.add(th);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
activeThreads.removeAll(activeThreads);
}
private int generator(int max, int min){
Random rand = new Random();
return rand.nextInt((max - min) + 1) - min;
}
public static void main(String[] args){
Server s = new Server();
s.createThreads();
s.executeThreads();
}
EDIT
SimulatedThreadComparator class
import java.util.Comparator;
public class SimulatedThreadComparator implements Comparator<SimulatedThread> {
#Override
public int compare(SimulatedThread o1, SimulatedThread o2) {
return o1.getId().compareTo(o2.getId());
}
}
That explains it: since the priority is the ID, the last thread that was activated will return to the head of the queue, and be the next activated, until it's finished.
Perhaps you should compare the executed time instead of the ID?

Categories