Solved

IOException

Posted on 2011-02-28
7
420 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
ID: 35004267
You have printStackTrace in the code; so which line throws IOException?

0
 

Author Comment

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

Expert Comment

by:for_yan
ID: 35004295
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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 92

Expert Comment

by:objects
ID: 35004425
           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
ID: 35005708
// 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
ID: 35044103
:)
0
 
LVL 92

Expert Comment

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

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Python Assistance 7 73
Java asynchronous logging 4 50
Securing Jmx Console and web console 2 65
Java passing arguments (type error) 2 48
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
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 will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

920 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

16 Experts available now in Live!

Get 1:1 Help Now