Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Page 1 of 2 12 LastLast
Results 1 to 25 of 34

Thread: Average length of time for input/output

  1. #1
    Member
    Join Date
    Nov 2012
    Posts
    49
    My Mood
    Amused
    Thanks
    10
    Thanked 0 Times in 0 Posts

    Default Average length of time for input/output

    Hi, here's my question

    After the threads have terminated the program should print out the average length of time (in ms)
    between the Producer inserting an integer and the Consumer removing that integer from the buffer.

    This is the last part of my assignment and I just can't grasp it. HEEEEEEEEEEEEEEEEEEEEEEEELP!!!



    here is my code

    import java.util.*;
    import java.io.*;
     
    class BoundedBuffer{
    	int nextIn,nextOut,size,occupied,ins,outs;
    	boolean dataAvailable = false;
    	boolean roomAvailable = true;
    	boolean timeElapsed = false;
    	int time = 1;
    	int [] buffer;
    	private final int BUFFERTIME = 5;
    	private long startTime,stopTime,totalTime;
     
    	public BoundedBuffer(int size){ 								//Constructor for buffer
    		this.size = size;
    		buffer = new int[size];
    	}
     
    	public synchronized void insertItem(int item) throws InterruptedException{    		//Method to add an item to the buffer
     
    		while(roomAvailable == false){    //Thread sleeps when there's no room in the buffer
    			wait();
    		}
    		buffer[nextIn] = item;
    		nextIn = (nextIn + 1) % size;
    		dataAvailable = true;
    		ins++;
     
    		startTime = System.currentTimeMillis(); // ***** GET TIME *****
     
    		occupied++;
    		System.out.println("Item Added. " + occupied);
     
    		if(occupied == size)
    			roomAvailable = false;
    		notifyAll();
    	}
     
    	public synchronized void removeItem() throws InterruptedException{ 
    																//Method to remove an item from the buffer
    		while(dataAvailable == false){
    			wait();
    		}
    		int tmp = buffer[nextOut];
    		buffer[nextOut] = 0;
    		nextOut = (nextOut + 1) % size;
    		outs++;
     
    		stopTime = System.currentTimeMillis(); // ****** GET TIME ******
                    totalTime +=(stopTime-startTime);
     
    		occupied--;
    		System.out.println("Item removed. " + occupied);
    		roomAvailable = true;
    		if(occupied == 0)
    			dataAvailable = false;
     
    		notifyAll();
     
    	} 
    	public synchronized void incTime() throws InterruptedException{
    		time++;
    		if(time == BUFFERTIME)
    			timeElapsed = true;
    	}
     
    	public long average(){
            long avg = totalTime/outs;
    		return avg;
        }
     
    }
     
    class Producer extends Thread{
    	private BoundedBuffer buffer;
     
    	public Producer(BoundedBuffer b){
    		buffer = b;
    	}
    	public void run(){ 
    		while(buffer.timeElapsed == false)
    		try {
    			int i = ((int)((Math.random()*100) + 1));
    			buffer.insertItem(i);
    			Thread.sleep((int)((Math.random()*100) + 1));
    		}
    	 	catch (InterruptedException e) {
    			System.out.println("Error in execution");
    		}
    	}
    }
    class Consumer extends Thread{
    	private BoundedBuffer buffer;
     
    	public Consumer(BoundedBuffer b){
    		buffer = b;
    	}
    	public void run(){ 
    		while(buffer.timeElapsed == false)
    		try {
    			buffer.removeItem();
    			Thread.sleep((int)(Math.random() * 100 + 1));
    	  	}
    	 	catch (InterruptedException e) {
    			System.out.println("Error in execution");
    		}
    	}
    }
    class Watcher extends Thread{
    	private BoundedBuffer buffer;
    	private final int BUFFERTIME = 5;
     
    	public Watcher(BoundedBuffer b){
    		buffer = b;
    	}
    	public void run(){
    		while(buffer.time <= BUFFERTIME){
    			try{
    				Thread.sleep(1000); //Sleep for 1 second in ms
    				System.out.println("Delta = " + ((buffer.ins-buffer.outs) - buffer.occupied) + 
    				" Occupied = " + buffer.occupied + " Time elapsed = " + buffer.time);
    				buffer.incTime();
     
    				if(buffer.time == BUFFERTIME){
    					System.out.println("Average Time = " + buffer..average());
    					System.out.println("Threads terminated. Goodbye for now");
    					System.exit(0);
    				}
    		    }
    			catch (InterruptedException e){
    				System.out.println("Error in execution");
    			}
    		}
    	}
    } 
     
    class Assignment_1{
    	public static void main(String [] args){
    		System.out.println("Please enter the size of the buffer: ");
    		Scanner in = new Scanner(System.in);
    		int size = in.nextInt();
    		in.close();
    		if(size <= 0){
    			System.out.println("Sorry, the size must be greater than 0.");
    			System.exit(0);
    		}
     
    		BoundedBuffer buffer = new BoundedBuffer(size);
    		Producer producer = new Producer(buffer);
    		Consumer consumer = new Consumer(buffer);
    		Watcher watcher = new Watcher(buffer);
    		producer.start();
    		consumer.start();
    		watcher.start();
     
    		try{
    			producer.join();
    			consumer.join();
    			watcher.join();
    		}
    		catch(InterruptedException e) { 
    			System.out.println("Error");
    		}
    	}
     
    }


    I can't seem to get my head around the average time for the question.

    Any help is greatly appreciated


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Average length of time for input/output

    Which part is the problem:
    Getting the time of insertion
    getting the time of removal
    computing the difference
    summing the times
    computing the average
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Member
    Join Date
    Nov 2012
    Posts
    49
    My Mood
    Amused
    Thanks
    10
    Thanked 0 Times in 0 Posts

    Default Re: Average length of time for input/output

    It's the average of the time from the Producer entering an integer and the consumer removing it.

    Getting the time of insertion
    getting the time of removal

    I can prob do the rest

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Average length of time for input/output

    The System class has a method that returns the PC's current time in a long.

    How will the code associate the time of insertion with the item that was inserted?
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Member
    Join Date
    Nov 2012
    Posts
    49
    My Mood
    Amused
    Thanks
    10
    Thanked 0 Times in 0 Posts

    Default Re: Average length of time for input/output

    Cool, I'll have a look, cheers.

    I have until Friday, so, I might be back haha

    --- Update ---

    I'v no idea

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Average length of time for input/output

    How about a class whose objects will hold the time of its insertion?
    If you don't understand my answer, don't ignore it, ask a question.

  7. #7
    Member
    Join Date
    Nov 2012
    Posts
    49
    My Mood
    Amused
    Thanks
    10
    Thanked 0 Times in 0 Posts

    Default Re: Average length of time for input/output

    And call the Producer as parameters and store it?

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Average length of time for input/output

    When an item is inserted, record the time in the object. When the item's object is removed, compute the duration.
    Save the item with the saved duration in a list somewhere.
    If you don't understand my answer, don't ignore it, ask a question.

  9. #9
    Member
    Join Date
    Nov 2012
    Posts
    49
    My Mood
    Amused
    Thanks
    10
    Thanked 0 Times in 0 Posts

    Default Re: Average length of time for input/output

    So, in the public synchronized void insertItem and public synchronized void removeItem the ins++ and outs++ can be used?

  10. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Average length of time for input/output

    SorrY I don't know what those counters are used for.
    I was talking about recording the clock time when an item is inserted and subtracting it from the clock time when the item is removed.
    If you don't understand my answer, don't ignore it, ask a question.

  11. #11
    Member
    Join Date
    Nov 2012
    Posts
    49
    My Mood
    Amused
    Thanks
    10
    Thanked 0 Times in 0 Posts

    Default Re: Average length of time for input/output

    They are used in The Watcher class's run method.

    I see what you mean but I'm a bit stuck in how to actually get that code working.

    Would I record the time with a statement eg if( buffer != 0) {record time} ??

  12. #12
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Average length of time for input/output

    There are printlns for when the item is added and when it is removed. Do they define the times of the two events you are interested in? If so, at the add, save the time in the item object. At the remove, compute the duration the item was in the buffer.
    If you don't understand my answer, don't ignore it, ask a question.

  13. #13
    Member
    Join Date
    Nov 2012
    Posts
    49
    My Mood
    Amused
    Thanks
    10
    Thanked 0 Times in 0 Posts

    Default Re: Average length of time for input/output

    They just count buffer run times.

    Yeah, I could capture the time between the add then remove in separate longs, compute it then print. I would have to use the amount of times it happens as well. So, that would be the ins and outs added together then divided by two. Add all the ms times the divide by the ins and outs calculation.

    Would I be correct? Maybe start and stop methods as well?

  14. #14
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Average length of time for input/output

    capture the time between the add then remove in separate longs
    Can there be more than one item in the buffer? If so, the times of the events should be kept with the item.

    What are the ins and outs used for? Would ins == outs at the end of the run? To make sure there are no losses.

    --- Update ---

    How are you going to test that the program computes the correct answer?
    If you don't understand my answer, don't ignore it, ask a question.

  15. #15
    Member
    Join Date
    Nov 2012
    Posts
    49
    My Mood
    Amused
    Thanks
    10
    Thanked 0 Times in 0 Posts

    Default Re: Average length of time for input/output

    The ins and out are used to tell you what's in the buffer and removed when it's ran ( as in quantity). Buffer size is set by the user.

    I don't think there's a specific answer at the end as I'd say everyone's will be different.

    I just compiled it for a buffer size of 10 and it finished added 10 and removed 9, so, it looks like the numbers aren't equal.

    It really has me a bit lost to be honest. I can post you the full questions and see if you can get a grasp on it. I'v asked a few in my class and they're the same.

  16. #16
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Average length of time for input/output

    I really don't have another suggestion. I've said the same thing now several times.

    If there is no test scheme to validate the results. Then will any answer work?
    It seems like a waste of time to compute a number if there is no way to validate its correctness.
    If you don't understand my answer, don't ignore it, ask a question.

  17. #17
    Member
    Join Date
    Nov 2012
    Posts
    49
    My Mood
    Amused
    Thanks
    10
    Thanked 0 Times in 0 Posts

    Default Re: Average length of time for input/output

    I know, if I code something I'v no way in checking if I'm right.. It seems a bit pointless with the type of project that's in it. I will try some of your suggestions, if no joy I will just loose 10 marks or something.

    Your time and help is greatly appreciated Norm.

  18. #18
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Average length of time for input/output

    I'v no way in checking if I'm right
    Then you do not understand the problem.

    Questions on the code:
    Why the hardcoded 10 in two places vs a single parameter to control the number of loops the code takes?
    Why does the Watcher class have a different loop control test from the other two classes?
    If you don't understand my answer, don't ignore it, ask a question.

  19. #19
    Member
    Join Date
    Nov 2012
    Posts
    49
    My Mood
    Amused
    Thanks
    10
    Thanked 0 Times in 0 Posts

    Default Re: Average length of time for input/output

    The hard 10 should be 60 as the question requests. I have it at 10 to speed up testing time. The watcher buffer time should be set to 60 as well. The sleep is set to 1000 milliseconds and print out results every second and buffer runs 60 times. You can get a better understanding if you compile it.

  20. #20
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Average length of time for input/output

    The code should NOT use hardcoded magic numbers. Values in variables should be used to control loops.

    I have compiled and executed it. I changed one of the 10 to a 2 for quicker testing and the code went into an infinite loop. That's why I suggested that hardcoded values should NOT be used.
    If you don't understand my answer, don't ignore it, ask a question.

  21. The Following User Says Thank You to Norm For This Useful Post:

    ManInTheMiddle (April 4th, 2013)

  22. #21
    Member
    Join Date
    Nov 2012
    Posts
    49
    My Mood
    Amused
    Thanks
    10
    Thanked 0 Times in 0 Posts

    Default Re: Average length of time for input/output

    Hi, I'v changed magic numbers to variables and added a timer class to calculate the average but it's returning 0.
    I'v been testing it and I think it returns a 0 because the start and stop have same values.


    Thanks again.

  23. #22
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Average length of time for input/output

    a timer class to calculate the average but it's returning 0.
    I'm not sure how that works. The time between events would be the difference between the time when an item is added and the time when it is removed.
    If you don't understand my answer, don't ignore it, ask a question.

  24. #23
    Member
    Join Date
    Nov 2012
    Posts
    49
    My Mood
    Amused
    Thanks
    10
    Thanked 0 Times in 0 Posts

    Default Re: Average length of time for input/output

    If I print the getTotalTime and totalTimeInMilis anywhere in the program for testing purposes I get 0. Surely it should return some sort of value

  25. #24
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Average length of time for input/output

    How are the values of those variables set? If they are not given values, their value would be 0.
    If you don't understand my answer, don't ignore it, ask a question.

  26. #25
    Member
    Join Date
    Nov 2012
    Posts
    49
    My Mood
    Amused
    Thanks
    10
    Thanked 0 Times in 0 Posts

    Default Re: Average length of time for input/output

    In the producer and consumer try blocks I have them being called. I'v edited it again and went about it a different angle but now
    I'm down to a single error in run time NullPointerException in Thread-2
    when the buffer ends. I think the logic to the rest is right.


    Sorry the site crashed there.

    Have it returning a number now. I think it's done.

Page 1 of 2 12 LastLast

Similar Threads

  1. Replies: 0
    Last Post: March 28th, 2013, 06:27 AM
  2. Input/Output help if possible
    By rossonomous in forum What's Wrong With My Code?
    Replies: 6
    Last Post: December 13th, 2011, 01:05 PM
  3. How do i limit the input time
    By itayj in forum Java Theory & Questions
    Replies: 6
    Last Post: October 24th, 2011, 03:47 PM

Tags for this Thread