This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
The moose likes Java in General and the fly likes Does this make sense? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Does this make sense?" Watch "Does this make sense?" New topic
Author

Does this make sense?

Eric Gero
Ranch Hand

Joined: Jul 20, 2005
Posts: 73
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

Joined: Jun 19, 2001
Posts: 547
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

Joined: Jul 11, 2001
Posts: 14112
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.


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Eric Gero
Ranch Hand

Joined: Jul 20, 2005
Posts: 73
That makes sense now, thank you both.
 
 
subject: Does this make sense?