Problem in static block execution

Hi all
i have a class which has a static block and a static method.For the first time i call the static method in the class its strange that its excuting a part of the static block and entering the method later and agian turning back to static block.
but for the secon time when i call the static method in that class its fine that static block is not executed..
here is the code of the class which contains static block and static method
public class LogServices
private static String propFilename="plas.properties";
private static String file="vdvd";
static
System.out.println("Inside static block");
try
System.out.println("Inside static block of Plasma Log Services ");
          file=PropertyProvider.getProperty(propFilename,"Log4jprops"); // here i am calling another method in another class to get some string from properties
System.out.println("\n File is ********************************** "+file);
catch(Exception e)
System.out.println("Exception encountered the following Exception ["+e.getMessage()+"]");
          System.out.println("Finished static block");
public static Logger initLog()
Logger logger=Logger.getLogger(PlasmaLogServices.class);
System.out.println("File in method is:"+file);
return logger;
and in my main program i am calling this
LogServices.initLog(); and the output i observed on the screen is
Inside static block
Inside static block of Plasma Log Services
File in method is:vdvd
File is ********************************** log.properties
Finished static block
if u look at the output after " Inside static block of Plasma Log Services" (part of static block) its enetering method where " File in method is:vdvd" is printed .
After some debugging i came to know that if i remove the line
file=PropertyProvider.getProperty(propFilename,"Log4jprops"); and replace it by file="log.properties";(mean hardcoded) then the static block executes and later that method executes.
can any one pls help me in this regard???

The first time you instantiate a class
LogServices, it's static block is being
executed.
After you've instantiated the class, you call its
static method.
If you call the static method again, the
LogServices have their static block already
executed, so it won't be executed again.
I think that the execution of static block and static
method is not mixed, as you thought. I think it is
rather a logging issue. Most loggers do not guarantee
that logging-messages are output in correct order.
Regards, TomHello sir
tahnks for ur reply and i got that .the problem was in the propertyprovider class i had a static variable logger =PlasmaLogservices.initLog() ; and hence after that it was by passing to that static method and coming back again .
thanks for looking in to this

Similar Messages

  • Stop Static Block Execution while loading class

    Hi,
    I want to load one class using Class. forname method. But with one condition that It should not execute static body of class.

    I would suppose that one had better really know what they are doing before using that method.

  • [Problem reading a file in a static block of code]

    Hi all,
    I'm trying to use a static block of code in an abstract class (let's say for initialisation). In this block I'm trying to read some lines of text from a file, and some FileNotFoundException are thrown,
    java.io.FileNotFoundException: file:/home/tom/workspace/cryptanalysis/data/keys (No such file or directory)
    java.io.FileNotFoundException: file:/home/tom/workspace/cryptanalysis/data/french_words (No such file or directory)
    but all the paths are valid and the files exist as you can see:
    tom@javahouse ~ $ ll /home/tom/workspace/cryptanalysis/data/
    total 24K
    -rw-r--r-- 1 tom users 151 jan 3 23:26 french_frequences
    -rw-r--r-- 1 tom users 2,0K jan 4 17:21 french_texts
    -rw-r--r-- 1 tom users 11K jan 4 17:16 french_words
    -rw-r--r-- 1 tom users 159 jan 4 17:21 keys
    tom@javahouse ~ $ cat /home/tom/workspace/cryptanalysis/data/french_words
    LE
    DE
    UN
    ETRE
    ET
    A
    IL
    AVOIR
    NE
    JE
    SON
    QUE
    SE
    QUI
    CE
    DANS
    I really don't understand why those exceptions are thrown, if somebody
    could help it would be very nice. (It is for a crypto school project)
    Thanks in advance. (Sorry for my english 'cause I'm french)
    Here is a code snippet :
    // Path to this class:
    // /home/tom/workspace/cryptanalysis/utils/TextUtils.java
    public abstract class TextUtils {
         private static String PATH;
         public static String[] KEYS;
         public static String[] WORDS;
         public static String[] PLAINTEXTS;
         public static float[] FREQUENCES;
          * Init KEYS, WORDS, PLAINTEXTS, FREQUENCES, and PATH,
          * with the files in the data folder.
         static {
              String line;
              PATH = TextUtils.class.getResource("../data/").toString();
              System.out.println(PATH);
              // When PATH is printed, it looks like this /home/tom/workspace/cryptanalysis/data/
              KEYS = FileUtils.readFileContent(PATH + "keys"); // Here is the first exception
              WORDS = FileUtils.readFileContent(PATH + "french_words");// Here is the second
              PLAINTEXTS = FileUtils.readFileContent(PATH + "french_texts");// Here is the third
              FREQUENCES = new float['['];
              try {
                   BufferedReader reader = new BufferedReader(new FileReader(PATH + "french_frequences"));// And the fourth
                   while(null != (line = reader.readLine()))
                        FREQUENCES[line.charAt(0)] += Float.parseFloat(line.substring(1));
              } catch (Exception e) {e.printStackTrace();}
    // Path to this class:
    // /home/tom/workspace/cryptanalysis/utils/FileUtils.java
    public abstract class FileUtils {
          * Read the content of the file denoted by the given path and
          * return an array of Strings containing each line.
          * @param path
          * @return an array containing all the lines from the file
         public static String[] readFileContent(String path) {
              try {
                   String line;
                   Vector container = new Vector(100, 100);
                   System.out.println(path);
                   BufferedReader reader = new BufferedReader(new FileReader(path));
                   while(null != (line = reader.readLine()))
                        container.add(line);
                   return (String[])container.toArray(new String[container.size()]);
              }catch(Exception e) {e.printStackTrace();return null;}
         ....

    vous �tes le type bienvenu
    (thats bablefish for "you're welcome dude")Wow! That means "vous �tes bienvenu" means "You are welcome here" (i.e., "welcome at the forum", or whatever), not the proper answer to "Thank you".
    The shortest form of "You're welcome" in the sense you intended it is "De rien". [literally, "of nothing"--so it would be something like if you said in English, "It was nothing."]

  • Foreach loop in static block won't compile

    When I try to compile this:public class TestEnum
      private static String[] numerals =
          {"einz", "zwei", "drei", "vier"};
      static
        for (String n : numerals)
          // doesn't matter what's in here
      public static void main(String[] args)
    }I get this exception:An exception has occurred in the compiler (1.4.2-beta).
    java.lang.NullPointerException
        at com.sun.tools.javac.comp.Lower.visitArrayForeachLoop(Lower.java:2269)
        at com.sun.tools.javac.comp.Lower.visitForeachLoop(Lower.java:2242)
        at com.sun.tools.javac.tree.Tree$ForeachLoop.accept(Tree.java:559)
        at com.sun.tools.javac.comp.Lower.translate(Lower.java:1580)
        at com.sun.tools.javac.tree.TreeTranslator.translate(TreeTranslator.java:51)
        at com.sun.tools.javac.tree.TreeTranslator.visitBlock(TreeTranslator.java:131)
        at com.sun.tools.javac.tree.Tree$Block.accept(Tree.java:497)
        at com.sun.tools.javac.comp.Lower.translate(Lower.java:1580)
        at com.sun.tools.javac.comp.Lower.visitClassDef(Lower.java:1645)
        at com.sun.tools.javac.tree.Tree$ClassDef.accept(Tree.java:409)
        at com.sun.tools.javac.comp.Lower.translate(Lower.java:1580)
        at com.sun.tools.javac.comp.Lower.translate(Lower.java:1594)
        at com.sun.tools.javac.comp.Lower.translateTopLevelClass(Lower.java:2438)
        at com.sun.tools.javac.main.JavaCompiler.compile(JavaCompiler.java:408)
        at com.sun.tools.javac.main.Main.compile(Main.java:523)
        at com.sun.tools.javac.Main.compile(Main.java:41)
        at com.sun.tools.javac.Main.main(Main.java:32)The same thing happens if I use foreach with a Collection instead an array. If I use an old-style for loop or Iterator in the static block, it compiles fine. I can also put the foreach loop in the main method, and it works. Is this a known bug?

    You guys rock. Thanks for finding this problem. I'll get it fixed.

  • LVOOP %27owning library blocked execution....%27

    Hi All
    I am working on a project using LabVIEW 8.5.1 (specfied by the customer not me!) and am having trouble with some LabVIEW classesI have created. I have created three classes - a parent class is a 'generic DAQ class', and card specific classes that inherit from the generic class overridding all methods. However I get an error that I can not get rid of... 'the owining library has blocked execution'. This is for all VIs and the class data types. I have opened the library using LabVIEW 2012 and 2013 and I do not get the same problem in either of those. Any thoughts?
    David
    www.controlsoftwaresolutions.com
    Solved!
    Go to Solution.

    I have found the issue. One of the overridng methods of one of the child clases did not have the 'dynamic dispatch' output terminal wired correctly - newer versions of LabVIEW must handle this better.
    David
    www.controlsoftwaresolutions.com

  • Problems with static member variables WAS: Why is the static initializer instantiating my class?!

    Hi,
    I have been hunting down a NullPointerException for half a day to come to
    the following conclusion.
    My constructor calls a method which uses static variables. Since an intance
    of my class is created in the static block when the class is loaded, those
    statics are probably not fully initialized yet and the constructor called
    from the static block has those null pointer problems.
    I've considered moving the initialization of the static variables from the
    declaration to the static block. But your code is inserted BEFORE any other
    code. Therefore not solving my problem.
    Two questions:
    1) what would be a solution to my problem? How can I make sure my static
    variables are initialized before the enhancer generated code in the static
    block calls my constructor? Short of decompiling, changing the code and
    recompiling.
    2) Why is the enhancing code inserted at the beginning of the static block
    and not at the end? The enhancements would be more transparent that way if
    the static variables are initialized in the static block.
    Thanks,
    Eric

    Hi Eric,
    JDO calls the no-args constructor. Your application should regard this constructor as belonging
    primarily to JDO. For example, you would not want to initialize persistent fields to nondefault
    values since that effort is wasted by JDO's later initilization to persistent values. Typically all
    you want to initialize in the no-args constructor are the transactional and unmanaged fields. This
    rule means that you need initialization after construction if your application uses the no-args
    constructor and wants persistent fields initialized. On the other hand, if your application really
    uses constructors with arguments, and you're initializing persistent fields in the no-args
    constructor either unintentionally through field initializers or intentionally as a matter of
    consistency, you will find treating the no-args constructor differently helpful.
    On the other hand, if Kodo puts its static initializer code first as you report, then it is a bug.
    Spec Section 20.16: "The generated static initialization code is placed after any user-defined
    static initialization code."
    David Ezzio
    Eric Borremans wrote:
    >
    Hi,
    I have been hunting down a NullPointerException for half a day to come to
    the following conclusion.
    My constructor calls a method which uses static variables. Since an intance
    of my class is created in the static block when the class is loaded, those
    statics are probably not fully initialized yet and the constructor called
    from the static block has those null pointer problems.
    I've considered moving the initialization of the static variables from the
    declaration to the static block. But your code is inserted BEFORE any other
    code. Therefore not solving my problem.
    Two questions:
    1) what would be a solution to my problem? How can I make sure my static
    variables are initialized before the enhancer generated code in the static
    block calls my constructor? Short of decompiling, changing the code and
    recompiling.
    2) Why is the enhancing code inserted at the beginning of the static block
    and not at the end? The enhancements would be more transparent that way if
    the static variables are initialized in the static block.
    Thanks,
    Eric

  • Static block in superclass to initialize static members in subclasses

    I am trying to create several classes that are all very similar and should derive from a super class because they all have common members and are all initialized the same way. I would prefer every member of my subclasses to be static and final as they will be initialized once and only once. I can not figure out the best way to make this work. Here is an example (using code that does not work, but you can see what I am trying to do):
    class Super
        protected static final String initializedInEachSubclass;
        protected static final String alsoInitializedInEachSubclass;
        // these need to be accessed from anywhere
        public static final String initializedInSuperclass;
        public static final String alsoInitializedInSuperclass;
        // this static initialization block is exactly the same for every instance
        static
            // initialize these based on what the subclasses initialized
            initializedInSuperclass = initializedInEachSubclass + alsoInitializedInEachSubclass;
        private Super () {} // never instantiated
        public static final String getMoreInfo ()
            // the same for each instance
            return Integer.toString (initializedInEachSubclass.length ());
    class Sub1 extends Super
        static
            initializedInEachSubclass = "My String for Sub1";
            alsoInitializedInEachSubclass = "My Other String for Sub1";
        private Sub1 () {} // never instantiated
    }The problem with the above code is that the static block in Super uses static final variables that have not been initialized yet. I can't make Super abstract. If I initialize the final variables in Super, then I can not reinitialize them in Sub1. But if they are not final, then they could be changed after being initialized (which I would rather not allow). I could make everything protected and not final and then make public get... () methods, but I like accessing them as attributes. It seems like this should be possible, but everything I have tried has led me to a catch-22.
    Any ideas on how I can put all my redundant initialization code in one place but still allow the subclasses to initialize the static members that make each of them unique? I will be happy to clarify my examples if you need more information.
    Edited by: sawatdee on Jan 3, 2008 9:04 AM

    sawatdee wrote:
    I am basically trying to avoid having redundant code in several classes when the code will be exactly the same in all of them.That's the wrong reason to subclass. You subclass to express type specialization. That is, a Dog IS-A Mammal, but it's a special type of Mammal that implements certain common mammal behaviors in a dog-specific way. A LinkedList IS-A List, but in implements common list operations in linked-list-specific ways.
    I don't really need to have the static final members in a superclass (and I don't even need a superclass at all), but I don't know how else to execute a big static initialization block in several classes when that code is exactly the same in all of them. Without knowing more details about what you're trying to do, this sounds like a case for composition rather than inheritance. What's now your superclass would be a separate class that all your "sublasses" have a reference to. If they each need their own values for its attributes, they'd each have their own instances, and the stuff that's static in the current superclass would be non-static in the "subs". If the values for the common attributes are class-wide across the "subs", the contained former super can be static.
    public class CommonAttrs {
      private final String attr1;
      private final int attr2;
      public CommonAttrs(String attr1, int attr2) {
        this.attr1 = attr1;
        this.attr2 = attr2;
    public class FormerSub1 {
      private static final CommonAttrs = new CommonAttrs("abc", 123);
    ... etc. ..

  • Exception handling in static block

    How to handle and exception raised in static block, pls answer

    Yeah, you are right, but I was just quoting the example on how to use it.
    Now, come to your problem,
    1. Static blocks are executed first time, when a class is loaded, i.e. when first reference of class is made.
    2. So, handle the situation there.
    E.g.
    You have test class:
    public class Test {
         static{
              try{
                   String s = null;
                   File f = new File(s);
              }catch(Throwable ne)
                   System.out.println("Eror");
                   throw new RuntimeException(); // Or use Error depends on your implementation
         public static void abc(){
              System.out.println("Hello");
    Now,
    calling it from another class:
    public class Test1 {
         public static void main(String[] args) {
              try{
              Test.abc(); *// This is the first instance where class for Test will be load and hence the static block will be executed*
              }catch(Throwable th) // Or catch Error
                   th.printStackTrace(); // Do the handling
              System.out.println("Done");
    This is a standard practice. From static block, instead of throwing Error exception, use some of your inherited class from Error. (i.e. create a exception framework inside your application)
    Hope this explains my point.

  • Weird Static Block Behaviour

    Hi There,
    I have a class to provide constants that is initialised using a static block...
    public final class ConstantNames {
        public static final String NAME1= "Name 1",
                NAME2= "Name 2",
                NAME3= "Name 3",
                NAME4= "Name 4",
                NAME5= "Name 5",
                NAME6= "Name 6",
                NAME7= "Name 7";
        private static final Set<String> VALUES;
        static {
            VALUES = CollectionsUtils.makeSet(NAME1, NAME2, NAME3, NAME4, NAME5, NAME6, NAME7);
        public static Set<String> values() {
            return VALUES;
         * Prevents construction.
        private ConstantNames () {
    }It works as expected in my local environment (Win XP/JDK 1.5) but in the production environment (Linux/JDK 1.5) It 'loses' NAME7 such that...
    ConstantNames.values().contains("Name 7")...returns false (its true for "Name 1" .. "Name 6")
    Can anyone shed any light on this for me - thanks

    On WinXP, its fine - you can add re-arrange doesn't make any difference. Its harder for me to make quick tests/changes in the Linux production environment. The latest change I'm releasing has done away with the static block so the Set is defined as...
    private static final Set<String> VALUES = CollectionsUtils.makeSet(NAME1, NAME2, NAME3, NAME4, NAME5, NAME6, NAME7);
    ...hoping (blindly) that this will make a difference. I'll see if I can do some more testing in the 'problem' environment without having to go through the whole release procedure.
    Thanks

  • Construct Derived Class in Static Block

    We've been having intermittent thread deadlock problems after migrating a stable system to Linux.
    One locked section we noticed occurred about 1 in 5 times, right at startup. The code looked fishy from the beginning, but I thought others could confirm whether it could be the cause of our problems.
    The code block constructs a derived class from a static block in the parent. Is it a recipe for failure? If so, why only intermittently and why not in Windows?

    The code block constructs a derived class from a
    static block in the parent.I don't understand that sentence. You have a block of code. It calls a constructor? It calls a constructor for a class that's derived from ... a static block? What do you mean?
    Is it a recipe for
    failure? If so, why only intermittently and why not
    in Windows?Intermittent failure is the nature of thread problems. Windows and Linux can have very different underlying implementations of threads.
    Show us some of the code and the failure mode.

  • Problem for releasing  blocked sales order on Creditlimit

    Hi Gurus,
            I a   hve a problem for releasing blocked sales orders
             what i have done: 1)i have blocked sales order based on exceeded creditlimit
             (i have change SDType in 'OVAK' is 'C')
                      2)now i have to release for furthur processing so i have done following steps
                      3)Goto VKM3/VKM1 T.Code and then release what order that is blocked.
                      4) order will appear in the list.
                      5)Select that one.
                      6)Click on the green flag that appears on the left hand side.
                      7)Click on save.
                      8)click on back it will ask for "Leave list".
                      9)Click on yes.
                      10)It said that Sales orer has been released
    Still what my problem is:
    Problem: 1)So i'm trying to create deliver for Sales order but it shows an error
             2)"Sales order is blocked for delivery: Credit limits" Even it was released    
    Plz kindly help  me what i do....
    Thanks In Advance
    sivakumar

    sorry   i was  unfotunately put this thread here  over in SD

  • Help required in understanding of static blocks in java

    Hi ,
    Can some one help me in understanding the difference between static blocks in java....also what is the difference in declaring some static variables in a class and and declaring some variables in a static block? From an architecture viewpoint when should one use static blocks in Java?

    Static blocks are piece of code that can beexecuted
    before creating an instance of a class.static blocks are executed once, when the class
    itself is loaded by the JVM. They are not executed
    before creating each instance of a class.
    For example whatever you include in the mainn method will be
    executed without you having to create the instanceof
    the class using the new operator. So you can saythe
    main method is a static block.main is not a static initialisation block but a
    static method. a special case static method at that -
    it is only executed when the containing class is
    specified as a parameter to the JVM. (unless you
    specifcally call it elsewhere in code - but that
    would be bad form).
    in answer to the original post, static variables
    belong to the class. each instance of the class share
    the same static variables. Public static vars can be
    accessed by prefixing them with the class name. A
    static initialisation block can be used to
    initialise static variables. Variables declared
    within the static initialisation block exist only
    within the scope of the block.
    e.g.
    public class Foo {
    static Bar bar;        // static member variable
    // static initialisation block
    static {
    // variable declared in static block...
    String barInfo =
    arInfo = System.getParameter("barInfo");
    // ... used to initialise the static var
    bar = new Bar(barInfo);
    So is the only purpose of static initialization blocks is to initialize static variables? Does the initialization of static variables inside a static block make any difference in performance? If yes , then how ?

  • Can we have try/catch in a static block in a class?

    hi All
    i have a question about put a try/catch block in a static block in a class to catch exceptions that maybe thrown from using System.xxxx(). in my custom class, i have a static block to initialize some variables using System.xxx(). in case of any error/exception, i need to be able to catch it and let the caller know about it. i tried to put a try/catch block in the static block, and tried to rethrow the exception. but it is not allowed, how would i handle situation like this? thanks for your help and advise in advance.

    You could just swallow the exception inside try/catch
    block, and instead of throwing it out, just set a
    static variable to allow checking from outside
    whether the initialization succeeded, or check within
    the constructor / methods of this class for
    successful initialization, and throw the exception
    then. You could even save that exception in a static
    variable for later.Ouch, ouch, you're hurting my brain. This would allow someone to ignore a (presumably) fatal error. Throw a RuntimeException as indicated. You can wrap a checked exception in an unchecked one if need be.

  • Use of functions in static block

    Hello,
    I have this app containing a static {} block. The reason it's there is to 1) provide a splash screen 2) have input dialog to process input string and check if it's valid in order to load app or not.
    In pseudocode it's like this:
    1 - get input string with showInputDialog()
    2 - check for the input string validity (a valid string is with prefix A-, C- or S-)
    3 - if string is valid, load the app
    4 - if string is not valid, proceed to step 1.
    As you may already see, there is going to be a lot of code (with if-else statements) to check for A-, C- and S- prefixed because I am using indexOf() function which takes only one parameter.
    I am considering a way to somehow check recursively, but for this I think I'll need a function to call indexOf() with A-, C-, S- and assess validity for each case.
    My question is, is there a way in the static block to have a function? Or can somebody please recommend an efficient approach to checking a string validity with different possibilities inside a static block as in my case, to avoid lots of if-else statements?
    P.S. My apologies for initially posting this thread in wrong section.
    Thank you!
    Victor.

    DrClap wrote:
    What's a function? And why are you particularly concerned about doing those things in a static initializer as opposed to in some other place?Hi,
    Sorry, I'm still thinking c++. I meant method. Something like of the form:
    static
    boolean valid = false;
    while string is not valid
    stringfrominput = showInputDialog();   
    //determine if string is valid
    valid = checkvalid(stringfrominput)
    //if possible to have
    boolean checkvalid(stringfrominput)
    recursively process stringfrom input based on A-, S-, or C- prefixes
    return boolean value
    }I have a jar app. It is Windows-based and runs as a TrayIcon application. If I include this process when class is loaded, this means that the app will be loaded with all its features. But I need to make sure that the app's features will be loaded only if certain conditions are met.
    I am not sure how else to approach this requirement without using static {} block.
    Thank you,
    Victor.

  • Non-blocking execution with Pro*C/C++

    Hi readers,
    Is there any mechanism available through which Non-blocking execution with Pro*C/C++?
    I observe that Pro*C queries are hanged when the DB server (hardware) is down.
    I understand that OCI provides non-blocking mechanisms. Pro*C doesn't use this OCI functionality?
    Regards,
    RajaGopal Maddi

    You can use TAF to handle your db down scenario.
    http://www.oracle.com/technetwork/database/app-failover-oracle-database-11g-173323.pdf

Maybe you are looking for