When I define static or constant members, for example:
public static final Font BIG_FONT = new Font("", Font.BOLD, 18);
I noticed that they only load when I first use them, which either results in freezes during the runtime or forces me to somehow preload them by forcefully 'using' the constant at the program launch.
Aren't static members of such type supposed to be loaded at program launch rather than wait to be loaded on first use? How can I make sure they are preloaded?
Thanks in advance.
In Java, statics are initialized when the class is first used, not when the static member itself is first used. You can force "pre-loading" by using any other member of that class, not necessarily the static field itself.
No.
Static initializers are executed when the class is first loaded.
The Java Runtime does not go out of its way to initialize every class as soon as you start the program; that would be a very bad idea.
what you can do is create a static loader method and include it in during your initialization method.
As others have mentioned statics are initialized when the class is first loaded.
One way to force this would be to either create an instance of the class in question or create (program) a distinct (new) class containing the statics and instantiate it as soon as the program starts. However, I'm not sure I would recommend either practice as they tie up memory that might be better used elsewhere.
Related
I have seen examples put all the By locator fields at the top as instance variables, but if they are only used once within a method surely they should be local? Which is cleaner and easier to read?
Even if they are used only once, its good practice to declare all the page elements at the class level. You may also mention it as static variable. A simple example for your perusal. Even though we use Hamburger icon only once, we still declare them at the top level. Since static variable, we are going to have only one object created for this at any point of time.
public class HomePage {
private static By byHamburgerIcon = By.xpath("//div[contains(#class,'icon-hamburger')]");
private static By byHeaderName = By.cssSelector("div[name='username']");
public void clickHamburgerIcon() {
PageActionHelper.click(byHamburgerIcon,"Clicked Hamburger icon");
}
}
This way it would be easier to refactor if any changes happened in future.
Also, there is high chance that we would use the locator in multiple places of the class. At those times, if we mention locator directly inside method, we would need to duplicate them. Changes on those locator need to be made everywhere. These are error prone. Hence having a single locator declared at the class level would be a better way.
I have an application with 100+ static variables and methods in its Application class will it affect the performance of the app? if so how to handle it?
As I see, your only question is if using static methods and variables inside your application class is wrong or not. As far as I know, it will not affect your application performance or anything else, but putting them inside application class is a wrong design. It's like you put all your code inside one single method and it will not be good.
So, I suggest you to put your static methods inside a Helper class and since they don't need to be instantiated, they need to be static, not a singleton. Also for your variables, for example for your Strings, I suggest to create another class and put them into it so your application maintenance be possible.
I have a class which my servlet instantiates on each page request. That class has a static initializer, a static variable and the rest contains non-static public or private members, a constructor, etc.
Is this safe? I don't want the static initializer to be called but only once throughout the lifecycle of my servlet.
Using Tomcat. I understand that each time the class is loaded by a Class Loader, the static initializer will be called. Should this be a concern for me (using tomcat) based on my requirement?
There are no problems, except if you modify the static variable since it'll be shared by all the requests. You will have concurrency issues if you do any decisions based on that variable.
Static initialization happens at class loading time, so that'll only happen once.
unless you maintain state in this second class you should not be worried about number of instantiations. A static initializer would serve just fine. There is no hard way to enforce "only once throughout the lifetime" behavior.
There are easy and plenty of hacks to turn your singleton to a multiton so I wouldnt worry about it. If you are a die hard fanatic for it use Spring or Pico else just dont maintain state in the second class only do stateless conversations with your servlet and all will be well.
I am building a webcrawler which is using two classes: a downloader class and an analyzer class. Due to my design of the program I had some methods which I outsourced to a static class named utils (finding the link suffix, determining if I should download it given some variables, etc.). Since at a certain time there is more than one downloader and more than one analyzer I'm wondering whether they can get a wrong answer from some static method in the utils class.
For example, say the analyzer needs to know the link suffix - it's using the utils.getSuffix(link) method. At that same time the OS switches to some downloader thread which also needs to get some link suffix and again uses utils.getSuffix(link). Now the OS switches back to the analyzer thread which does not get the correct response.
Am I right?
In case I'm right should I add synchronized to every method on the utils class? Or should I just use the relevant methods in every thread to prevent that kind of scenario even though I'm duplicating code?
This entirely depends on the implementation of the method. If the method uses only local variables and determines the suffix based on the parameter you give it, all is well. As soon as it needs any resource that is accessible from another thread (local variables and parameters are not) you'll need to worry about synchronization.
It seems to me you're using statics as utilities that don't need anything outside their own parameters; so you should be safe :)
I have an odd situation where i want to be able to be able to persist a variable in memory.. like a global variable I can pin in the JVM.
Is this possible? I remember doing something similar in college, but can't find it by googling. I have a logic problem that has some artificial constraints that make this the best possible solution.
EDIT 1:
I will need to update the value of the variable.
EDIT 2 :
I appreciate the responses guys. I'm a .net programmer and hadn't used java since college. Thanks again.
Yes, using a static field:
public class GlobalVariableHolder {
public static int globalVariable;
}
Note, however, that this is considered a bad practice and can lead to unexpected results that are hard to debug. The way to not use a global variable is to pass it around as an argument or methods where you need it.
If you are still sure you need this, in order to guard yourself as much as possible, use synchronization. Even better, if the variable is going to be primitive (int, long, etc), you can use AtomicInteger's getAndAdd() or addAndGet() method.
Usually you will end up storing these things in some kind of a global class--a class that is accessible from anywhere and has a controlled number of instances.
Singletons are commonly used for this. If you look up the pattern for a singleton and store your variable in that singleton (add a setter and a getter) you are on your way.
Doing this (as opposed to a public static variable) will give you some level of access control and traceability--for instance you can put debug statements in the getter if you find you are getting unpredictable results.
In the long run setters and getters and singletons are all bad code smells but no where near as bad as a settable public variable.
Later you may want to move the code that manipulates that variable into the singleton object and possibly convert the singleton to something you can fetch via IOC, but having a singleton is a much better place to start than with a public static.
Do you mean something that will exist across multiple invocations of java.exe, or do you mean a single variable that will be the same location in memory regardless of which thread within java.exe access it? Or do you mean a variable that can only be accessed if you're using JRockit? Or maybe just the JVM on your dev machine, but not on another system?
In the first case, you'd need another way to store it, like a config file.
In the second case, like Bozho says, use the static keyword.
In the third case, you'd probably need to use the System class and determine the JVM manufacturer (Assuming that's available from System - I'm not sure off the top of my head, and you'll learn more by looking up the API yourself).
In the fourth case, you're pretty much back to a config file.
Its not going to win any awards but this should work:
package mypackage;
public class MyGlobal {
public static String MY_GLOBAL_VAR = "my variable";
}
Any class within that JVM instance would be able to access MyGlobal.MY_GLOBAL_VAR.
Updated to allow update.