Quiz J5-2 | CS 2113 Software Engineering - Spring 2021

Quiz J5-2

Submit your answers via this Google Form

Question #1

A second price auction is an auction where the highest bidder only has to pay
whatever the second highest bid was. For example if person A bids $1 and person
B bids $2, then person B wins the auction, but only pays $1. Below are two
classes that reflect this:

class Auction {
    private int currentHighestBid = 0;
    private int secondHighestBid = 0;

    public int getSecondHighestBid() {
        return secondHighestBid;
    }

    public void makeBid(int amount) {
        if (amount > currentHighestBid) {
            secondHighestBid = currentHighestBid;
            currentHighestBid = amount;
        }else if(amount > secondHighestBid)
            secondHighestBid = amount;
    }
}

class Bidder extends Thread {
    Auction auction;
    int maxBid;

    public Bidder(Auction auction, int maxBet) {
        this.auction = auction;
        this.maxBid = maxBet;
    }

    public void run() {
        try {
            Thread.sleep((new Random()).nextInt(10));
        } catch (Exception e) {
            e.printStackTrace();
        }
        auction.makeBid(maxBid);
    }
}

In this version of the auction, our bidders bid the highest amount they are willing to spend, and that is all.

What is the output of the program below:

    public static void main(final String args[]) {
          Auction auction = new Auction();
          Bidder[] bidders = new Bidder[3];
          for (int i = 0; i < bidders.length; i++)
              bidders[i] = new Bidder(auction, i + 1);

          for (int i = 0; i < bidders.length; i++)
              bidders[i].start();
          for (Bidder p : bidders) {
              try {
                  // Ensures all threads have finished before we print out the price
                  p.join();
              } catch (Exception e) {
                  e.printStackTrace();
              }
          }
          System.out.println("Final Price"+auction.getSecondHighestBid());
    }

Question #2

We then add volatile in front of currentHighestBid and
currentSecondHighestBid as shown below:

class Auction{
    private volatile int currentHighestBid = 0;
    private volatile int secondHighestBid = 0;
    ...
}

What is the output if we run the program from question #1 again?

Question #3

Now we add synchronized in front of makeBid as shown below:

class Auction{
    public synchronized void makeBid(int amount) {
    ...
    }
    ...
}

What is the output if we run the program from question #1 again?