Hi, I wanna run Java class only once, meaning that if I have a class "abc", I execute it using java abc, then again do the same thing java abc, the second time around should give me an error. How do I go about it??? Haven't done it before... Thanks in advance
hi, im not all around sure, but what if you have a static int variable in the main class that you set to 0. the first thing you do in the main method is to increase it by one. then you check if the value of this variable is higher than one. if it is, then exit. hope it helps. tormod
This is a classic example of the Singleton pattern. It is implemented as the folks above described. -You need a static variable to indicate how many instances have been made. -You need to make sure that your constructor is private so that the only way to create an instance of the class is to use a method of the class. -You need a static method, say createInstance() or whatever that checks the static variable and makes the decision whether or not to call the private constructor. If you want to allow only one instance AT A TIME (instead of one instance ever), then you will also need to have a static method to get rid of the previous instance and reduce the counter back to zero.
"JavaRanch, where the deer and the Certified play" - David O'Meara
Joined: Jul 31, 2001
If you're running it "java abc" each time, and want the concept of only having run once to carry across the different JVM instances, then go with a filelocking, inifile or a registry solution. Using the singleton pattern is only valid within a given session of a JVM. Making the reason clear as to why you want to do this may shed some light on the best approach to take. ( only run once on a user's machine, in the class' existince?!? )