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

Similar Messages

  • Static fields ARE being serialized

    Hi there,
    I wrote a small test class that serializes an object, writes the serialized object to file, read the serialized object from the file and then deserialize the object. The object being serialized contains normal fields, a transient field, and a few 4 static fields with varying access modifiers. For some reason the static variables ARE being serialized. From what I've read this should not happen, and for very good reasons.
    Here is the object being serialized:
    package serialization;
    import java.io.Serializable;
    import java.util.Formatter;
    public class MySerializableObject implements Serializable {
         private static final long serialVersionUID = 1L;
         private int a = 1;
         private int b = 2;
         private transient int c = 3;
         static public int d = 4;
         static protected int e = 5;
         static private int f = 6;
         static int g = 7;
         @Override
         public String toString() {
              Formatter formatter = new Formatter();
              formatter.format("a=%1$s b=%2$s c=%3$s d=%4$s e=%5$s f=%6$s g=%7$s", a,b,c,d,e,f,g);
              return formatter.toString();
         public void setNewD(int newVal) {
              d = newVal;
    }And here is the code that does the serialization:
    package serialization;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    public class FileContentsObjectSerializer {
         File file;
         public FileContentsObjectSerializer(String name) {
              this.file = new File(name);
              if (this.file.exists()) {
                   this.file.delete();
              try {
                   this.file.createNewFile();
              } catch (IOException e) {
                   e.printStackTrace();
         public void serialize(Object o) throws IOException {
              FileOutputStream fos = new FileOutputStream(this.file);
              ObjectOutputStream oos = new ObjectOutputStream(fos);
              oos.writeObject(o);
              oos.close();
              fos.close();
         public Object deserialize() throws IOException, ClassNotFoundException {
              FileInputStream fis = new FileInputStream(this.file);
              ObjectInputStream ois = new ObjectInputStream(fis);
              Object o = ois.readObject();
              fis.close();
              ois.close();
              return o;
         public static void main(String args[]) {
              MySerializableObject mso = new MySerializableObject();
              mso.setNewD(100);
              System.out.println("Object being serialized:"+mso.toString());
              FileContentsObjectSerializer ofs = new FileContentsObjectSerializer("c:/temptest.txt");
              try {
                   ofs.serialize(mso);
                   MySerializableObject result = (MySerializableObject) ofs.deserialize();
                   System.out.println("Deserialized Object:    "+result.toString());
              } catch (Exception e) {
                   e.printStackTrace();
    }And here is the results I get:
    Object being serialized:a=1 b=2 c=3 d=100 e=5 f=6 g=7
    Deserialized Object:    a=1 b=2 c=0 d=100 e=5 f=6 g=7As you can see, both results are exactly the same, even though the setNewD value is not called on the deserialized object.
    Any ideas?

    You are misinterpreting the result. Try this main instead:
        public static void main(String args[]) {
            MySerializableObject mso = new MySerializableObject();
            mso.setNewD(100);
            System.out.println("Object being serialized:"+mso.toString());
            FileContentsObjectSerializer ofs = new FileContentsObjectSerializer("c:/temptest.txt");
            try {
                ofs.serialize(mso);
                mso.setNewD(-100); //a-oogah!
                MySerializableObject result = (MySerializableObject) ofs.deserialize();
                System.out.println("Deserialized Object:    "+result.toString());
            } catch (Exception e) {
                e.printStackTrace();
        }

  • 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.

  • 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.

  • 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

  • Reducing amount of discrete vector objects [Acr 8]

    Any way to simplify vector objects in a PDF file?
    I have a page with complex maps. This PDF is placed in InDesign, scaled, and then I export to create a new PDF. Either at the source (linked PDF) or the final PDF, I'd like to simplify the vector map images, presumably by rasterizing to 72 ppi.
    Any way to do this in Acrobat?
    Thanks in advance,
    Aaron

    Hi..
    >
    SET LINESIZE 200
    COLUMN username FORMAT A15
    SELECT s.username,
    s.sid,
    s.serial#,
    t.used_ublk,
    t.used_urec,
    rs.segment_name,
    r.rssize,
    r.status
    FROM v$transaction t,
    v$session s,
    v$rollstat r,
    dba_rollback_segs rs
    WHERE s.saddr = t.ses_addr
    AND t.xidusn = r.usn
    AND rs.segment_id = t.xidusn
    ORDER BY t.used_ublk DESC;
    >
    HTH
    Anand

  • Losing field (in a Composit Object) in an HttpSession

    Hello. I am losing fields in a Composite object (object tree) that I am storing inside of an HttpSession. I'm developing with Tomcat and I saw that Tomcat implements the put/getAttribute methods with a Hashtable.
    So in my case, I store object A. in an HttpSession. For a user requests, I get A. and do some processing that sets object D. If I put that object back into the session and come back to it in a later request, object D has now been lost.
    A
    B
    C
    D
    Is there some contract that I'm missing here? I don't think these objects (A - D) need to be serialized. What am I missing here?
    Thanks in advance
    Tim

    It is very difficult to figure out what is going wrong from the info u have given. Examine your server log carefully if you can find any clue.
    You may also write a listener implementing HttpSessionAttributeListener and implement the methods
    attributeAdded(HttpSessionBindingEvent) ,attributeRemoved(HttpSessionBindingEvent) ,attributeReplaced(HttpSessionBindingEvent) to write some meaningful message in logs.
    Track the message generated by attributeRemoved() method in particular to find out when exactly is your object D going out of session. May be that will give u some clue. You can use HttpSessionBindingEvent.getName() and
    HttpSessionBindingEvent.getValue() methods to know about the object added/removed/reset in your session that has invoked the particular method in your listener.
    Also you will need to register the listener class in your web.xml for that to work properly.
    You will find more examples/help of this listener in net if u do a google search.

  • 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.

  • 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

  • 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.....

  • Static fields

    Can anyone tell me how compiler compiles static or 'final static' fields? Are they holding memory for whole period time of process, or when they're dereferenced, memory will be reclaimed during the process?
    Thanks

    I am fraid last response misunderstood my question
    and comments. Say there are 5000 static integers in
    application. It is 5000 bytes. Then there are 5000
    static String fields and each has 40 characters (each
    one is two bytes). Total static String may have
    400000 bytes. Each time the class that contains these
    fields is referenced at run time they take up memory.So are you saying that if these fields are not static? It wouldnot take memory? Or are you suggesting that there would always be only one instance of each of these classes so you wouldnot take more space if these fields are not static?
    So when application runs forever, it will have a
    great chance all these static will be loaded into
    memory. So total is 405K bytes that is 'permanently'
    stay in memory. You can claim this still a small
    amount. But this is just an example and everythingFirst of all its totally insignificant as to how much memory is being taken. The reasons under consideration for declairng a variable static are totally different from what you are assuming but even if you think this way let me tell you this much making them member variables would take more memory since now these variables would be associated with their respective instances and not the class object. And donot tell me that each of these classes is going to have only on instance, so multiply the value with the no. of instances, if you could tell how many instances you would have.
    is relative, depending on runtime system. So this is
    my original questions: if I want to do something to
    save a little bit memory that is permanently occupied
    by these static stuffs. But I like to know how
    compiler and runtime work: is that true if class is
    dereferenced, static field memory will be also
    reclaimed? If that is true, I don't need worry (that
    means these static fields do not 'permanently' stay
    in memory. If not true, I will review these fields toThis question has been answered in my previous post.
    see which one could be defined as instance fields or
    even defined on stack. The trade off always on
    allocate memory on globe heap and keep reference to
    it, or create object as needed.
    From your comments, seems you think both static and
    instance fields can be reclaimed memory if they are
    dereferenced (only difference is static is one copy
    and instance has multiple - that's obviously and not
    question we need discuss)Again you are wrong over here. Read the replies posted again. Secondly I repeat members are not defined static or regular based on the constraints you have in mind and secondly, the way you are thinking that the memory model works is totally wrong. To cut the story short you would not save any memory but making these members regular (non static) On the other hand you might break things by stepping into unknown terrotory since you are not trying to comprehend why were they made static in the first place.

  • Different behaviour reading static field Windows vs Linux

    I have a class B that is a subclass of class A. Class A has a protected static field. In windows, reading this field from a static method of class B yields the desired results, meaning that the field has the value updated somewhere else. Running the same code in Linux, the field contains the value assigned to it at declaration time:
    It goes like this:
    package packageA;
    public class A
    protected static Collection items = new ArrayList();
    public static void addItem(Object item)
    items.add(item);
    } // class A
    package packageB;
    public class B
    extends A
    public static void methodA()
    System.out.println(A.modules.size());
    System.out.println(B.modules.getSize());
    System.out.println(modules.size());
    } // class B
    import packageA.A;
    import packageB.B;
    public static void void main(String[] args)
    Object item;
    item = new String("");
    A.addItem(item);
    B.method();
    } // main(String[])
    What is even more strange, is that if I run the above example in a new project, the results are as expected. But if I run this other project I am working on, the results are as if B.items is independent of A.items. Even if I implement a method A.getItems() and call it from B.method() to store the items in a variable local to B.method(), the result is an empty ArrayList.
    My first attempt was to place the A and B classes in the same package, and since the results were as expected, I changed each class to its own package and the Main class to an independent package. The results do not change in this scenario.
    Your help is appreciated.
    The environment is:
    Netbeans 5.5
    JRE 1.6.0-b105
    xubuntu (Linux 2.6.20-16-generic i686 GNU/Linux(
    Juan Carlos

    I have just noticed that the "odd" behaviour does not happen everywhere (but it does happen everytime).
    I realized that there is another part of code that references the same static field and the value in that case is the correct one.
    Also, while debugging under Netbeans (on the line of code that gives the unexpected value), the "tip" that is displayed when the cursor is placed over the name of the field, the value is correct.
    So I decided to check the Call Stack and noticed some Hidden Source Calls. They are hidden because of a call to LoginContext.login() Furthermore, that call results in a call to AccessController.doPrivileged()
    Could that be the problem? If so, how do I solve it. At this point I am lost here, I don't have an idea of where to go now.
    Thanks.
    JC

  • Is a static var 'copied' when and object is cloned?

    HI,
    If you have an abstract class that has a static object as a property,
    i.e.
    public abstract class xyz implements Cloneable, Runnable {
    static Manager M;
    Thread runner;
    and a concrete class is created by cloning this object, i.e.
    public void run(){
    if(x!=null){ // if we are the server process
    while (runner!=null){
    try{
    Concrete_xyz = (Concrete_xyz) clone(); // (Concrete xyz implements xyz)
    Concrete_xyz.x = null;
    Concrete_xyz.runner = new Thread(Concrete_xyz);
    Concrete_xyz.runner.start();
    }catch(Exception e){}
    }else{
    run(client);
    will all the clones share the static Manager object? ....is this a stupid question?
    any help much appreciated

    Well, not a stupid one, just kinda obvious. There is one and only one copy of each static field for any loaded class. The only time there would be more than one is when more than one class loader loads the class, in which case the classes are truly the same (just happen to have the code).
    Cloning, serialization/deserialization, etc. will never duplicate static fields.
    Chuck

  • 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.

  • Field value(s) for object S_SERVICE were not entered

    Hi
    Whenever I try to generate a profile in PFCG I get an error, that is saying;
    ... field value(s) for object S_SERVICE were not entered
    Number of values could be different but message text is always the same.
    The problem is in CRM2007 IDES.
    It is regardless if I try to generate for existing role (like SAP_CRM_UIU_MKT_PROFESSIONAL) or for own role
    Does anybody know how to solve such issue ?
    regards
    Rafal

    Dear Rafal,
    kindly check documentation of customizing node
      SAP Customizing Implementation Guide
        Customer Relationship Management
          UI Framework
           Business Roles
             Define Authorization Role
    "Make sure that the authorization object S_SERVICE is set to inactive.
    An active authorization object S_SERVICE could interrupt the profile
    generation."
    You have to deactivate the S_SERVICE authorization object in PFCG to
    solve the error.
    Hope this helps,
    Gerhard

Maybe you are looking for

  • OS X mountain lion wont download

    I have just purchased the new OS X but it wont download. Is anyone else having problems. i have contacted apple (non)support but they are harder to get hold of than the pope! Do any apple support contact numbers actually work?

  • Color printing shift in Epson 3800 & InDesign CS5

    Somebody please help! I wrote about this once before and have been looking for a thread to help me figure out why I am having so much trouble printing from my Epson 3800, since I upgraded to CS5. The issue is specific to InDesign and Acrobat. I have

  • FireTreeNodesInserted doesn't work

    I am using TreeModel, not the DefaultTreeModel. When I insert a node, the first always works fine, but the following don't show up on the tree. I tried everything I could think of but doesn't. I have also noticed that the second insertion changes the

  • Closing msn account

    hi have a question about to change your account from a microsoft account to iCloud account get all your apps with you to a new iCloud i have 200 gb storage how do i do that is the a formular i have only problem using a microsoft account  is stopping

  • Script conflict resolution

    A couple of questions. 1. I'm using a lightwindow and spry on the same webpage. Does anyone know if the sprydata.js file from 1.4 conflicts with lightwindow.js, scriptaculous.js., and prototype.js. If so then I'll just remove the lightwindow on that