Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Does this make sense?

 
Eric Gero
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you look at my code below, can you tell me what is happening when I make a static FileReader file, then set file = new FileReader(fileName) each time I open a file. Does it make sense for FileReader file to be static? I realize that by making file static, I will only ever have one instance of file, but is this efficient or smart coding?

Thanks,
Eric

private static BufferedReader reader;
private static FileReader file;
private List list = new LinkedList();

private WTFRParseFile() {
}
private static WTFRParseFile wtfr = new WTFRParseFile();

public static WTFRParseFile makeWTFR() {
return wtfr;
}
public void openFile(String fileName) throws FileNotFoundException, IOException {
file = new FileReader(fileName);
reader = new BufferedReader(file);
}
[ April 17, 2006: Message edited by: Eric Gero ]
 
pascal betz
Ranch Hand
Posts: 547
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
try to make references as local as possible. if it is only used in the method then delcare it in the method. that much about the visibility or scope of the reference.

if you make the reference static, then ALL instances of the class will SHARE the reference -> it is not thread safe anymore.


pascal
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Eric Gero:
I realize that by making file static, I will only ever have one instance of file


That's not true. You will only have one shared "file" variable, but that's only the *reference*. Every time you call a constructor (such as the new FileReader... in your code), you are creating a new object.

Making the variable a static field won't do you any good at all.
 
Eric Gero
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That makes sense now, thank you both.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic