Solved

IOException

Posted on 2011-02-28
7
414 Views
Last Modified: 2012-05-11
I am currently developing a cache cohrence protocol in java but I am having an IOException when reading my trace file and i have no idea why. Below is the codes generating the error.
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Hashtable;


public class CacheSim {
	public int simIndex;
	public Hashtable<Integer, String> myCache; 
	public int notValid;													
	public static int hRate;
	public static int mRate;
	public static int noProcessors = 4;
	private static String processor;
	private static String state;
	private static String word;
	private static int cacheLocation;

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		CacheSim cacheSim = new CacheSim();
		File traceFile = new File("C:\\Users\\mjarju\\Documents\\Uni Stuff\\Course Work\\Prallel Architecture\\Assignments\\Assignment2\\memtrace.txt");
	    FileInputStream takeInTrace = null;
	    BufferedInputStream streamData = null;
	    DataInputStream streamOperation = null;
	    boolean switch_off = false;
	    String state_value;
	    CacheSim []proc=new CacheSim[noProcessors];

	    try {
	      takeInTrace = new FileInputStream(traceFile);

	      // Here BufferedInputStream is added for fast reading.
	      streamData = new BufferedInputStream(takeInTrace);
	      streamOperation = new DataInputStream(streamData);
	      String readLine;

	      // dis.available() returns 0 if the file does not have more lines.
	      while (streamOperation.available() != 0) {
	    	  readLine = streamOperation.readLine();
	    	  
	    	  //========================================================
	    	  
	    	  if(readLine.length()>1){	    		  
	  	         processor = readLine.substring(0,2);	        
	  	         state = readLine.substring(3,4);
	  	         word = readLine.substring(5);
	  	         cacheLocation = Integer.parseInt(word);
	  	    	}

				if(readLine.length()==1)
				{


					if(readLine.equals("i"))
					{
						System.out.println("Total number of Invalids"+ " " + cacheSim.notValid);
						for(int i=0;i<noProcessors;i++)
							System.out.println("Invalidation on Processor "+ i+ " = "+ proc[i].simIndex);
					}
					else if(readLine.equals("h"))
					{
						System.out.println("hit rate is"+" "+hRate);
						System.out.println("miss rate is"+" "+mRate);
					}
					if(readLine.equals("v"))
					{
						if(switch_off==true)
						{
							switch_off=false;
						}
						else
						{
							switch_off=true;
						}
					}
					if(readLine.equals("p"))
					{
						System.out.println(proc[0].myCache);
						System.out.println(proc[1].myCache);
						System.out.println(proc[2].myCache);
						System.out.println(proc[3].myCache);
					}
				}
				else
				{ 
					if(state.equals("l"))
					{
						state_value="loads";
					}
					else
					{
						state_value="store";
					}
					if(switch_off==true)
					{
						System.out.println("a"+ " "+ state_value + "form"+state+ "to word"+word );
					}
					
	    	  //==============================================================

	      // this statement reads the line from the file and print it to
	        // the console.
//	        System.out.println(streamOperation.readLine());
//	    	  if(readLine.length()>1){	    		  
//	        String processor = readLine.substring(0,2);	        
//	        String state = readLine.substring(3,4);
//	        String word = readLine.substring(5);
//	        int cacheLocation = Integer.parseInt(word);
//	    	  }
	      }	 
	      // dispose all the resources after using them.
	      takeInTrace.close();
	      streamData.close();
	      streamOperation.close();
	      }
	    } catch (FileNotFoundException e) {
	      e.printStackTrace();
	    } catch (IOException e) {
	      e.printStackTrace();
	    }
	
	
	}	
	
	
	
	public boolean getCachValue(int memoryLineKey)									
	{
		if(this.myCache.containsKey(new Integer(memoryLineKey)))
			return true;						
		else
			return false;
	}
	
	public int locationOnCache(int size, int lineNos, int memoryLineKey)
	{
		int location= (memoryLineKey>>size);
		int INTmaximymLength=2147483647;
		int mov=(31-lineNos);
		int max=(INTmaximymLength>>mov);
		int cacheLocation=((location) & max);
		return cacheLocation;
	}

}

Open in new window

0
Comment
Question by:Atouray
  • 2
  • 2
  • 2
  • +1
7 Comments
 
LVL 47

Expert Comment

by:for_yan
Comment Utility
You have printStackTrace in the code; so which line throws IOException?

0
 

Author Comment

by:Atouray
Comment Utility
           while (streamOperation.available() != 0) { line 45
0
 
LVL 47

Expert Comment

by:for_yan
Comment Utility
Didin't you try to change it
to something like  

while((readline=stream.readLIne())! = null) {...}

 should be the same
but perhaps there are some subtle differences
 
0
Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

 
LVL 92

Expert Comment

by:objects
Comment Utility
           takeInTrace.close();
            streamData.close();
            streamOperation.close();

looks like you're closing the streams *inside* the loop
0
 
LVL 86

Accepted Solution

by:
CEHJ earned 500 total points
Comment Utility
// dis.available() returns 0 if the file does not have more lines.

That's not really the case:

a. it only reports the number of bytes that can be read *without blocking*
b. it doesn't guarantee that number of bytes will be read - you should normally read a file until EOF

In fact you can simplify your code greatly by using a Scanner (see below)

Also, consider using the lighter and faster HashMap rather than the legacy class Hashtable
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import java.util.Hashtable;
import java.util.Scanner;


public class CacheSim {
    public static int hRate;
    public static int mRate;
    public static int noProcessors = 4;
    private static String processor;
    private static String state;
    private static String word;
    private static int cacheLocation;
    public int simIndex;
    public Hashtable<Integer, String> myCache;
    public int notValid;

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        CacheSim cacheSim = new CacheSim();
        File traceFile = new File(
                "C:/Users/mjarju/Documents/Uni Stuff/Course Work/Prallel Architecture/Assignments/Assignment2/memtrace.txt");
        boolean switch_off = false;
        String state_value;
        CacheSim[] proc = new CacheSim[noProcessors];

        try {
            Scanner sc = new Scanner(traceFile);
            String readLine = null;

            while (sc.hasNextLine()) {
                readLine = sc.nextLine();

                //========================================================
                if (readLine.length() > 1) {
                    processor = readLine.substring(0, 2);
                    state = readLine.substring(3, 4);
                    word = readLine.substring(5);
                    cacheLocation = Integer.parseInt(word);
                }

                if (readLine.length() == 1) {
                    if (readLine.equals("i")) {
                        System.out.println("Total number of Invalids" + " " +
                            cacheSim.notValid);

                        for (int i = 0; i < noProcessors; i++)
                            System.out.println("Invalidation on Processor " +
                                i + " = " + proc[i].simIndex);
                    } else if (readLine.equals("h")) {
                        System.out.println("hit rate is" + " " + hRate);
                        System.out.println("miss rate is" + " " + mRate);
                    }

                    if (readLine.equals("v")) {
                        if (switch_off == true) {
                            switch_off = false;
                        } else {
                            switch_off = true;
                        }
                    }

                    if (readLine.equals("p")) {
                        System.out.println(proc[0].myCache);
                        System.out.println(proc[1].myCache);
                        System.out.println(proc[2].myCache);
                        System.out.println(proc[3].myCache);
                    }
                } else {
                    if (state.equals("l")) {
                        state_value = "loads";
                    } else {
                        state_value = "store";
                    }

                    if (switch_off == true) {
                        System.out.println("a" + " " + state_value + "form" +
                            state + "to word" + word);
                    }
                }
            }

            // dispose all the resources after using them.
            sc.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public boolean getCachValue(int memoryLineKey) {
        if (this.myCache.containsKey(new Integer(memoryLineKey))) {
            return true;
        } else {
            return false;
        }
    }

    public int locationOnCache(int size, int lineNos, int memoryLineKey) {
        int location = (memoryLineKey >> size);
        int INTmaximymLength = 2147483647;
        int mov = (31 - lineNos);
        int max = (INTmaximymLength >> mov);
        int cacheLocation = ((location) & max);

        return cacheLocation;
    }
}

Open in new window

0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
:)
0
 
LVL 92

Expert Comment

by:objects
Comment Utility
Good to see my suggestion fixed your problem :)
your use of available() had nothing to do with it
0

Featured Post

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now