Static field initialization

Ok, I know this was a good practices issue in C++, where order of initializing static fields from different source files was unknown, but I'm not sure if Java is smart enough to figure it out.
So, say you have in one file
public class A{
   public static B b = new B();
}And in the other:
public class C{
   private static D  d = A.b.getD();
}Will this always work? Or does it depend on the order in wich classes A and C are loaded.

jschell wrote:
In multiple threads on some systems (potentially) the construction of B() is not guaranted before access to 'b' is allowed.Class initialization is synchronized, so the construction of B() should be fully visible to other threads without explicit synchronization or making the field final.
From JLS 12.4.3:
Code generators need to preserve the points of possible initialization of a class or interface, inserting an invocation of the initialization procedure just described. If this initialization procedure completes normally and the Class object is fully initialized and ready for use, then the invocation of the initialization procedure is no longer necessary and it may be eliminated from the code-for example, by patching it out or otherwise regenerating the code.So class initialization is attempted whenever the code generator feels it might be the first use of a class.
And from 12.4.2:
The procedure for initializing a class or interface is then as follows:
1. Synchronize (§14.19) on the Class object that represents the class or interface to be initialized. This involves waiting until the current thread can obtain the lock for that object (§17.1).
2. If initialization is in progress for the class or interface by some other thread, then wait on this Class object (which temporarily releases the lock). When the current thread awakens from the wait, repeat this step.So the class is synchronized on until initialization (which includes all static initializers) finishes. This makes possible the class holder idiom for singletons.

Similar Messages

  • Using Objects to Initialize Static Fields: Good or Bad

    I have a Command interface and a bunch of Commands that implement it (i.e. CmdJoin,CmdQuit). These Commands' settings change at runtime (i.e. required access levels, String identifiers). I don't want to have to store an instance of each Command in a database to save their settings , so instead I'm using the obvious solution: making static fields in these commands for these settings. This way, I can use a Simple Factory to return a Command, change its settings, execute it, and forget it, and still have the settings for that Command apply to all Commands. Yet I want to be able to modify and access fields of different Commands polymorphically. How can I have these commands' settings-related fields be static while modifying and accessing these fields polymorphically?
    Here's what I have though of. First of all, interfaces can't have static methods. Secondly, neither can abstract classes. I also can't extend a base class which implements these settings-related fields and their interface, because then the fields would belong to all child classes of this base class, whereas I just want it to belong to a certain child class of the base class (i.e. all instances of CmdJoin or CmdQuit).
    I've thought of two solutions.
    The first is implementing a concrete interface in an abstract base class (getting rid of the Command interface) and overriding it in child classes, so that I can use the interface of the base class and the fields of the child classes.
    The second is having no base class, and just a bunch of Commands implementing the interface with their own static fields. I would initialize these fields by passing arguments to their constructors.
    These solutions seem very sloppy though! Are there any better ways?

    To clarify, I want all objects of type A to be able to respond to a static method declared in type A yet still remember their implementation of this static method. I provided two solutions that I have thought of, and I find them sloppy, so I'm asking if there's a better way.

  • Is read-only access to a static field correct without volatile/locking?

    Hello,
    I wonder wether the following code is safe:
    static UnicomServerCentral instance;
         public static void setInstance(UnicomServerCentral central)
              synchronized (UnicomServerCentral.class)
                   instance = central;
         public static UnicomServerCentral getInstance()
              UnicomServerCentral central = thisinstance;
              if (central == null)
                   synchronized (UnicomServerCentral.class)
                        central = this.instance;
              return central;
         }The static field instance is already guaranteed to be set. Is this safe?
    Thank you in advance, lg Clemens

    It might be safe in a particular context if there is
    additional synchronization involving the construction
    of the the "central" object and the execution of any
    threads that might call getInstance.Well if getInstance() returns null I simply spin as long as I get a non-null value back - so the only circumstance I could get here null is initialization.
    Since this example is a perfect does-not-work-dcl example I'll search the net for exmplanations.
    Thanks a lot, lg Clemens

  • How to ensure multiple nested classes static readonly initialization orders

    Hello,
    I am emulating the Java Enumeration in a first class class, with static readonly field initialization.
    In an effort to further categorize some instances, I embed them in nested classes. Something like this.
    class A : Enumeration
    public static class CatB
    public static readonly A FirstInstance = new B();
    public static readonly A SecondInstance = new B();
    public static class CatC
    public static readonly A ThirdInstance = new C();
    public static readonly A FourthInstance = new C();
    class B : A
    class C : A
    So far so good.
    One strain of Enumeration has built-in Ordinals, so I initialize them in the static ctor, or I make an effort to.
    static A()
    var values = GetValues().ToList();
    var ordinal = 0;
    values.ForEach(v => v.Ordinal = ++ordinal);
    Also, in places, so far so good.
    However, in a main method, I am referencing one of the enumerated instances, so calls to my GetValues() is returning nulls for that nested class. The other nested class instances are just fine, they return just fine.
    I could post more, but I think this illustrates the idea.
    I am suspicious that a strange static initialization order is jumbled up, as evidenced by nested static ctor debug statements I put in. I get one print and not the other.
    When I switch up which instance I reference in my main, I get the opposite behavior, more or less confirming my suspicions.
    So... Question is, what's the best way to potentially work around this issue? Hopefully without abandoning the Enumeration concern altogether, but that thought is a possibility as well. Or at least do so differently.
    Thank you...

    It is probably necessary to show GetValues() at least. I am getting the correct nested types, so that much we can at least assume.
    protected static IEnumerable<TDerived> GetValues()
    var declaringTypes = GetDeclaringTypes(typeof (TDerived)).ToArray();
    foreach (var declaringType in declaringTypes.Reverse())
    var fis = declaringType.GetFields(PublicStaticDeclaredOnly);
    var values = fis.Select(fi => fi.GetValue(null)).ToArray();
    foreach (var value in values.OfType<TDerived>())
    yield return value;
    Okay, here a bit of explanation.
    Enumeration is declared generically, with TDerived as the derived type. In this case, A.
    GetDeclaringTypes is operating okay. I get types for A, B, and C.
    The fis to values is breaking down, however. When I reference any of the CatB's, I get nulls for those instances. Conversely, same for CatC's when I reference any of those.

  • How can I share a static field between 2 class loaders?

    Hi,
    I've been googling for 2 days and it now seems I'm not understanding something because nobody seems to have my problem. Please, somebody tell me if I'm crazy.
    The system's architecture:
    I've got a web application running in a SunOne server. The app uses Struts for the MVC part and Spring to deal with business services and DAOs.
    Beside the web app, beyond the application context, but in the same physical server, there are some processes, kind of batch processes that update tables and that kind of stuff, that run once a day. Theese processes are plain Java classes, with a main method, that are executed from ".sh" scripts with the "java" command.
    What do I need to do?
    "Simple". I need one of those Java processes to use one of the web app's service. This service has some DAOs injected by Spring. And the service itself is a bean defined in the Spring configuration file.
    The solution is made-up of 2 parts:
    1. I created a class, in the web app, with a static method that returns any bean defined in the Spring configuration file, or in other words, any bean in the application context. In my case, this method returns the service I need.
    public class SpringApplicationContext implements ApplicationContextAware {
         private static ApplicationContext appContext;
         public void setApplicationContext(ApplicationContext context) throws BeansException {
              appContext = context;
         public static Object getBean(String nombreBean) {
              return appContext.getBean(nombreBean);
    }The ApplicationContext is injected to the class by Spring through the setApplicationContext method. This is set in the Spring configuration file.
    Well, this works fine if I call the getBean method from any class in the web app. But that's not what I need. I need to get a bean from outside the web app. From the "Java batch process".
    2. Why doesn't it work from outside the web app? Because when I call getBean from the process outside the web app, a different class loader is executed to load the SpringApplicationContext class. Thus, the static field appContext is null. Am I right?
    So, the question I need you to please answer me, the question I didn't find in Google:
    How can I share the static field between the 2 class loaders?
    If I can't, how can I load the SpringApplicationContext class, from the "Java batch process", with the same class loader my web app was started?
    Or, do I need to load the SpringApplicationContext class again? Can't I use, from the process, the class already loaded by my web app?
    I' sorry about my so extensive post...
    Thank you very much!

    zibilico wrote:
    But maybe, if the web service stuff gets to complicated or it doesn't fulfill my needs, I'll set up a separate Spring context, that gets loaded everytime I run the "Java batch process". It'll have it's own Spring configuration files (these will be a fragment of the web app's config files), where I'll define only the beans I need to use, say the service and the 2 DAOs, and also the DB connection. Additionally, I'll set the classpath to use the beans classes of the web app. Thus, if the service and DAOs were modified in the app server, the process would load the modified classes in the following execution.You'll almost certainly have to do that even if you do use RMI, Web services etc. to connect.
    What I suggest is that you split your web project into two source trees, the stuff that relates strictly to the web front end and the code which will be shared with the batch. The latter can then be treated as a library used by both the batch and web projects. That can include splitting Spring configuration files into common and specific, the common beans file can be retrieved from the classpath with an include. I regularly split web projects this way anyway, it helps impose decoupling between View/Controller and Model layers.
    On the other hand, you might consider running these batch processes inside the web server on background threads.

  • Adobe Reader files missing information in static fields after being emailed?

    Hello, I have emailed the same person three seperate times with an attached PDF file that does have some fillable fields and some static fields. One time I email them the file, and the data in the static fields has been changed, but the fillable fields are the same, so I emailed it again and this time all the fields are completely blank, any ideas?

    Email transmissions can do all kinds of things, including attachments getting damaged or lost.  Far better and safer is to use a file sharing service like Acrobat.com, Dropbox, Google Drive, ..., then send the link by email.

  • The static field should be accessed in a static way

    Hello,
    I am developing a java app in eclipse and I am getting the error message:
    The static field Calendar.DAY_OF_WEEK should be accessed in a static way
    I am trying to get the first day of the first week in the current month, here is my code:
    GregorianCalendar firstDayOfThisMonthCalendar = new GregorianCalendar(Calendar.YEAR, Calendar.MONTH, 1);
    int firstDayOfThisMonth = firstDayOfThisMonthCalendar.DAY_OF_WEEK;I though the problem was that I'm supposed to write the code like this:
    firstDayOfThisMonthCalendar.get(Calendar.DAY_OF_WEEK); but then I get the wrong value back

    That's what I critice about u people, always ready to
    complain, It's not complaining. It's pointing out problems with your code. You should thank him.
    but do u put the code in here the way that
    someone could read it ? Easy to say 'use
    simpleDateFormat. Oh, careful, January returns 0, not
    1'.Using SimpleDateFormat is an easier and more correct way to do it. Trying to use the numerical value of the month constants is incorrect coding. You should thank him for educating you.
    Why can't u write the code in here so there's no
    chance that somebody will ask again.Such code is not possible. No matter what code you write, somebody can misunderstand it.
    If you write the code correctly--using SimpleDateFormat--then the code will be correct (which is the most important criteria) and clear (which is important, but not as important as correctness).
    But if you prefer to think that your way is always perfect and are afraid to admit your mistakes and learn from them, that's your prerogative.

  • Static field should be accessed in a static way

    I am getting the following warning message: static field should be accessed in a static way. What does it mean?
    thanks.

    Below is the code. I'm getting the "warning" in the Waiter class on the statement: this.r = r;
    public class Threads {
         public Threads() {
              super();
              System.out.println("==> Threads.constructor");
         public static void main(String args[]){
              System.out.println("==> main");
              Threads t = new Threads();
              Rendezvous r = new Rendezvous();
              Waiter w1 = new Waiter(r);w1.start();
              Waiter w2 = new Waiter(r);w2.start();
              Waiter w3 = new Waiter(r);w3.start();
              new Waiter(r).start();
              new Waiter(r).start();
              new Waiter(r).start();
              new Waiter(r).start();
              Waiter w4 = new Waiter(r);w4.start();
              Waiter w5 = new Waiter(r);w5.start();
              Waiter w6 = new Waiter(r);w6.start();
              System.out.println("==> main done");
         static class Rendezvous{
              private static int ri = -1;
              public synchronized void doWait(Waiter w){  
                   System.out.println("==> doWait - sNum="+w.serialNum+",tries="+w.numTries+" name="+Thread.currentThread().getName());
                   while (w.numTries < 5){
                        notifyAll();
                        w.numTries++;
                        System.out.println("==> before wait()- sNum="+w.serialNum+",tries="+w.numTries);
                        try {wait();} catch (InterruptedException e){}
                        System.out.println("==> after wait() - sNum="+w.serialNum+",tries="+w.numTries);
                   } //end-while
              } //end-doWait()
              public void doNotify(){
                   notify();
         } //end-Rendezvous-class
         static class Waiter extends Thread{
              private static int counter = 1000;
              private static Rendezvous r;
              public int serialNum;
              public int numTries = 0;
              public Waiter(Rendezvous r){
                   this.r = r;
                   serialNum = counter++;
                   System.out.println("==> Waiter.counstructor:sNnum="+serialNum+" name="+Thread.currentThread().getName());
              public void run(){
                   System.out.println("==> Waiter.run():" + serialNum+" name="+Thread.currentThread().getName());
                   r.doWait(this);

  • Static field changes for both instances

    Whenever I construct a new object with a static field or use a set method on any of the instances of that object, the static field will change to the last modification made. In the case of my program, whenever the static String color field is changed to the last modification made. This only happens with the static fields, the other fields work just fine.
    Why does this problem occur?

    Sorry, I can't understand the question. If you have lots of different objects, all of the same class, they all share one copy of the static field, so if you invoke a method that changes the static field on one instance, all the other instances will see that change.
    if you don't want this behaviour, don't make the field static; then each instance will have its own copy of the field.

  • Static fields in serialized Vector objects

    just a curious question:
    If I have a Vector filled with Objects of all the same type, and the Object contains a static field, and I then Serialize the Vector, will it still give better performance than if the field wasn't static? Thanks,
    Max

    nevermind - found out the hard way that static fields won't get Serialized

  • Generics in static fields

    Hi, I am trying to make a class which has some generic fields. I understand that it would not work just like that as the compiler has no way what the generic fields should actually be in a static context.
    I want to use the generic class as an abstract class which would be extended, so that way the generics should be resolvable. Is there any way to make this work this way or should I not use generics and go type unsafe?
    This is what I want to do in code:
    abstract class ClassToBeExtended<A>
         static A a;
    class UsingTheOther extends ClassToBeExtended<String> {}

    It is supposed to be a class that adds relations between other classes:
    // Simplified
    class RelationBetweenAandB extends TheClass<A, B> {}
    class SomeOtherClass
      void foo()
        A a = new A();
        B b1 = new B();
        B b2 = new B();
        RelationBetweenAandB.add(a, b1);
        RelationBetweenAandB.add(a, b2);
        new YetAnotherClass().listRelationsOf(a);
    class YetAnotherClass
      public void listRelationsOf(A a)
          for (B b : RelationBetweenAandB.allRhs(a))
          ; // Iterate through b1 and b2
    }Having static fields will make the relation useful from anywhere in the application, if it is not static then all the objects that are going to be used in a relation have to instantiate the class which wlll probably introduce a lot of overhead.
    abstract class SomeClass<A extends OtherClass>
      static OtherClass a;
    } Would require me to have Object in stead of OtherClass because I want all types of object to be in a relation, which is what I meant by going type unsafe :)
    Message was edited by:
    SavageNLD
    Added some more reasoning about why I want static fields

  • Static field and subclasses

    If a parent class with a private static field has 5 subclasses, each with a private static field of the same name as the parent field and the parent has an accessor method for this field, will each of the 5 subclasses return its own version of the field if the accessor method is called (from the children of course)? The method is not overridden in the subclasses.

    Did you try it and see what would happen?

  • Static field component in virtual machine spec

    Hello.
    I can&#8217;t understand some point in JavaCard Virtual Machine Specification v2.2.2.
    Section: 6.10 Static Field Component. See table 6-14. segment 4 &#8211; it describe &#8220;primitive types initialized to non-default values&#8221;. It is describes by two parameters : non_default_value_count, non_default_values[].non_default_values &#8211; is image of all static primitive fields independence of it type &#8211; byte, short, int. This image consist from data in big-endian order.
    How I can use it at architecture with little-endian order?
    I can&#8217;t parse where short or int &#8211; I can&#8217;t convert it. How I can do it?

    As you pointed out it is not known from the CAP file format where single short or int values begin. At access time you know where the value starts and of which type it is. Therefore it looks like you have no choice but to convert the value at every access from or to big endian.
    This is from a design perspective definitely not nice regarding the VM design but I don't think the performance penalty is too costly.

  • StreamTokenizer static fields

    Maybe this is a stupid question but why does this compile without problems:
    Reader r = new BufferedReader(new InputStreamReader(System.in));
    StreamTokenizer tok = new StreamTokenizer(r);
              // StreamTokenizer tok = new StreamTokenizer(System.in);
              try{
                   while (tok.nextToken() != StreamTokenizer.TT_EOF){
                        switch (tok.ttype) {        // ttype is token type
                             case StreamTokenizer.TT_NUMBER: 
                                  System.out.println("number " + tok.nval);
                                  break;
         ....But this:
    Reader r = new BufferedReader(new InputStreamReader(System.in));
    StreamTokenizer tok = new StreamTokenizer(r);
              // StreamTokenizer tok = new StreamTokenizer(System.in);
              try{
                   while (tok.nextToken() != StreamTokenizer.TT_EOF){
                        switch (tok.ttype) {        
                             case tok.TT_NUMBER:  // nval is numeric value
                                  System.out.println("number " + tok.nval);
                                  break;
         ....                    gives the following compiling error:
    constant expression required
        case tok.TT_NUMBER:  value
               ^
    1 errorI thought static fields can be access both through the name of the class and objects of it.
    The version that doesn't compile comes from a book which makes it slightly more confusing.

    excuse my wording. I have been using >= mostly, though
    I do know that > exists. If I replace the >
    with >= and compile there are no errors. But I also
    get the following errors with the >
    # javac TestLight.java
    TestLight.java:13: ')' expected
    if (a.KWH_PRICE > 0)
    ^
    TestLight.java:13: not a statement
    if (a.KWH_PRICE > 0)
    ^
    TestLight.java:13: ';' expected
    if (a.KWH_PRICE > 0)
    ^
    TestLight.java:13: cannot resolve symbol
    symbol : variable gt
    location: class TestLight
    if (a.KWH_PRICE > 0)
    ^
    4 errorsYou really get errors then ?
    Very strange, I don't get any.....

  • Avoid assigning to servlet static fields without using a shared lock??

    Hi
    i received the following warning on my code, does anyone give me a help on this? Thanks
    "Avoid assigning to servlet static fields from javax.servlet.Service.service () without using a shared lock."
    And my code are as follow:
    public class MyDataSource {
        private static DataSource ds = null;
        public static DataSource getDataSource() throws NamingException, Exception
            if (ds==null){
                   InitialContext ctx = new InitialContext();
                try{
                    synchronized(getDataSource()){
                    if(ds==null){
                        ds = (DataSource) ctx.lookup(SysProperties.ds);
                } catch (Exception ex) {
                    throw new Exception("DBConnection Exception: " +ex.toString());
                }finally{
                        if(ctx !=null){
                            ctx.close();
            return ds;       
    }

    The service method of a servlet is multi-threaded to handle multiple requests. Hence,any static or public fields accessed by the service method should be restricted to a single thread access (for example using synchronized keyword) to make it thread-safe. That is why you are getting the warning message.

Maybe you are looking for