How to persistent static object

JDO always assigns a StateManager to a PersistenceCapable object when
creating instance. If an object is static, it'll keep its StateManager for
ever after instantiation. So If I excute the following code repeadly, kodo
will complain that persistence manager has been closed.
1) Get PersistenceManager
2) Begin transaction
3) Get object from datastore. If not exist, create a new object. This
object is a static.
4) Commit transaction
5) pm.close
For the first time, kodo will assign a new StateManager to this static
object. But for the second time, exception, "persistence manager has been
closed", will arise when excuting some of object's methods. Because each
StateManager object owns a PersistenceManager object. If this pm is
closed, according StateManager object is also useless.
After enhancing, kodo will change some getter/setter methods to
according jdo getter/setter ones. These methods may invoke
startManager.isLoaded(), which invokes pm.isActive(). Unfortunately, pm
has been closed.
Any other tricky methods to persistent static object ?
Thanks !

Dear Marc,
Thanks for your kind help. It's an effective advice to prevent
persistent object from being static.
However, what if the object to be persistent is an enumeration type
constant ? For example :
public class MyEnumType
private String name = null;
private int value = 0;
protected MyEnumType( String name, int value )
this.name = name;
this.value = value;
public static final TYPE_1 = new MyEnumType( "type 1", 1 );
public class EnumTypeUseClass
private MyEnumType type = null;
public void setType(..) {..}
public MyEnumType getType() {..}
public class TestClass
public void f()
PersistenceManager pm = null;
try
// Obtain pm
pm = ...;
pm.currentTransaction().begin();
EnumTypeUseClass use = new EnumTypeUseClass();
// Obtain myenumtype object from datastore
MyEnumType type = getJdoObject( pm, MyEnumType.class, "value ==" +
MyEnumType.TYPE_1.getValue() );
// Following line will cause "PersistenceManager has been closed"
exception
use.setType( type );
pm.makePersistent( use );
pm.currentTransaction().commit();
catch( .. )
finally
pm.close();
public static void main( String args[] )
for( int i = 0; i < 10; i ++ )
f();
Actually, exception is caused by MyEnumType.TYPE_1.getValue() because
this object's pm has been closed in the first loop time.
Now I solved this problem by not persistent MyEnumType objects, and
change type field in EnumTypeUseClass from MyEnumType to int.
But I still wonder how to persistent static objects.
Maybe your first advice is feasible, but I think it will make your
program tangly. Do you think so ? :)
Marc Prud'hommeaux wrote:
Liang-
You are correct that a persistent instance must be associated with a
PersistenceManager. You could always just leave the PersistenceManager
open (if using optimistic transaction, Kodo won't tie up database
resources in this case). Another option is to not have the singleston
instance be a static variable, but have it be obtained via a factory
method that takes a PersistenceManager argument.
If this doesn't help, perhaps you could help clarify the situation by
posting some code that shows that you would like to do?
In article <[email protected]>, Liang Zhilong wrote:
JDO always assigns a StateManager to a PersistenceCapable object when
creating instance. If an object is static, it'll keep its StateManager for
ever after instantiation. So If I excute the following code repeadly, kodo
will complain that persistence manager has been closed.
1) Get PersistenceManager
2) Begin transaction
3) Get object from datastore. If not exist, create a new object. This
object is a static.
4) Commit transaction
5) pm.close
For the first time, kodo will assign a new StateManager to this static
object. But for the second time, exception, "persistence manager has been
closed", will arise when excuting some of object's methods. Because each
StateManager object owns a PersistenceManager object. If this pm is
closed, according StateManager object is also useless.
After enhancing, kodo will change some getter/setter methods to
according jdo getter/setter ones. These methods may invoke
startManager.isLoaded(), which invokes pm.isActive(). Unfortunately, pm
has been closed.
Any other tricky methods to persistent static object ?
Thanks !
Marc Prud'hommeaux [email protected]
SolarMetric Inc. http://www.solarmetric.com

Similar Messages

  • Persistent static

    Does anybody have a recommendation on good way to get the effect of a
    persistent static object (ie. one persistent instance for all objects of a
    persistent class)?
    Scott

    If you mean one shared PC instance, you can have a facade to store the
    oid of that single object for use by each specific instance:
    public class Foo
         private static Object oid = null;
         // ... persistent attributes here ...//
         public static Foo getSharedInstance (PersistenceManager pm)
              if (oid == null)
                   Extent e = pm.getExtent (Foo.class, false);
                   oid = JDOHelper.getObjectId
                        (e.iterator ().next ());
              return pm.getObjectById (false);
    Of course this is untested, but you get the idea. Then in when you deal
    with Bar instances sharing that Foo, you can simply do something along
    the lines of
         Bar bar = new Bar ();
         bar.setFoo (Foo.getSharedInstance (pm));
    Scott Leschke wrote:
    Does anybody have a recommendation on good way to get the effect of a
    persistent static object (ie. one persistent instance for all objects of a
    persistent class)?
    Scott
    Stephen Kim
    [email protected]
    SolarMetric, Inc.
    http://www.solarmetric.com

  • How to cast an Object into a specific type (Integer/String) at runtime

    Problem:
    How to cast an Object into a specific type (Integer/String) at runtime, where type is not known at compile time.
    Example:
    public class TestCode {
         public static Object func1()
    Integer i = new Integer(10); //or String str = new String("abc");
    Object temp= i; //or Object temp= str;
    return temp;
         public static void func2(Integer param1)
              //Performing some stuff
         public static void main(String args[])
         Object obj = func1();
    //cast obj into Integer at run time
         func2(Integer);
    Description:
    In example, func1() will be called first which will return an object. Returned object refer to an Integer object or an String object. Now at run time, I want to cast this object to the class its referring to (Integer or String).
    For e.g., if returned object is referring to Integer then cast that object into Integer and call func2() by passing Integer object.

    GDS123 wrote:
    Problem:
    How to cast an Object into a specific type (Integer/String) at runtime, where type is not known at compile time.
    There is only one way to have an object of an unknown type at compile time. That is to create the object's class at runtime using a classloader. Typically a URLClassloader.
    Look into
    Class.ForName(String)

  • How to set a object value bound to a session to JavaScript variable

    In a JSP, I store an object value in a HttpSession and I also write a Javascript function to display something on the screen. I need to use the Javascript function to display the object value which is stored in the session. How to set the object value to variable of the JavaScript function. Thanks.

    I write a class JavaScriptHelper to convert the object value to variable of the JavaScript;
    1.get the data to a javabean from database;
    2.convert the data to variable of the JavaScript as a String ;
    3.store the object in a HttpSession or Httprequest ;
    4.use in Jsp get the String (variable of the JavaScript )
    YourBean bean = (YourBean) request.getAttribute("model");
         if (bean != null) out.println(bean .getJsCode())
    convert function,(this is only for the matrix):
    public static String formatJsCode(Vector vector) {
    String sJsCode = "";
    //get js head
    sJsCode = getJsHeader();
    //define js array;
    sJsCode += "var data=new Array();\n";
    Vector v = null;
    String sTemp = "", sLine = "";
    for (int i = 0; i < vector.size(); i++) {
    v = (Vector) vector.get(i);
    sLine = "";
    for (int j = 0; j < v.size(); j++) {
    sTemp = (String) v.get(j);
    //replace " to \"
    sTemp = sTemp.replaceAll("\"", "\\\\\\\"");
    //escape Html Tag
    //sTemp = StringUtil.escapeHTMLTags(sTemp);
    //replace \r\n to <br>
    sTemp = sTemp.replaceAll("\r\n", "<br>");
    if (j != 0)
    sLine += ",";
    sLine += "\"" + sTemp + "\"";
    sJsCode += "data[" + i + "]=new Array(" + sLine + ");\n";
    //get js foot
    sJsCode += getJsFooter();
    return sJsCode;
    public static String getJsHeader(){
    return "<script language=\"JavaScript\">";
    public static String getJsFooter(){
    return "</script>";
    }

  • How to set a Object value by JDI

    How to set a Object value using JDI?
    For example:
    class User{
      private String name;
      private String id;
    set and get method;
    public static void main(String[] args) throws Exception {
            VirtualMachineManager vmm = Bootstrap.virtualMachineManager();
            List<AttachingConnector> connectors = vmm.attachingConnectors();
            SocketAttachingConnector sac = null;
            for (AttachingConnector ac : connectors) {
                if (ac instanceof SocketAttachingConnector) {
                    sac = (SocketAttachingConnector) ac;
                    break;
            if (sac == null) {
                System.out.println("JDI error");
                return;
            Map<String, Connector.Argument> arguments = sac.defaultArguments();
            Connector.Argument hostArg = arguments.get("hostname");
            Connector.Argument portArg = arguments.get("port");
            hostArg.setValue(HOST);
            portArg.setValue(String.valueOf(PORT));
            vmMachine = sac.attach(arguments);
            List<ReferenceType> classesByName = vmMachine.classesByName(CLSNAME);
            if (classesByName == null || classesByName.size() == 0) {
                System.out.println("No class found");
                return;
            ReferenceType rt = classesByName.get(0);
            List<Method> methodsByName = rt.methodsByName(METHODNAME);
            if (methodsByName == null || methodsByName.size() == 0) {
                System.out.println("No method found");
                return;
            Method method = methodsByName.get(0);
    I will connect to server and monitor the remote server JVM , There is a object of User, I want to change its value by the Java Debugger Interface by client.
    so how to set its value by the client, and I can not got the User bean at client.
    I know the basic type filed value changed as follows:
    Value newValue = vmMachine.mirrorOf("change var value");// this field is a string.
    stackFrame.thisObject().setValue(field, newValue);
    But a Object , how can I change its value.
    Thanks Advanced.

    ObjectReference.setValue() is the method for chaining the value of an Object's field. First you need to find the specific Object you want to change, though.
    /Staffan

  • How to make an object mutable?

    Can any one tell me how to make an object mutable?
    Following is Class X & Y?
    class Y
    public static void main(String arg[]) {
    X a1=new X();
    Object a=a1.get();
    System.out.println(a.toString());
    a1.set(a);
    System.out.println(a.toString());
    class X implements Serializable
    public Object get(){
    return new Object();
    public synchronized void set(Object o)
    o=null;
    In my class Y when i say
    a1.set(a);
    I want local Object a of main method should be nullified.
    Can it be possible if yes what is the way or code to be applied so that
    my next a.toString() statement will give me NullpointerException.

    Isn't it more accurate to say that object references are passed by value?
    OP -- Basically you can't to what you want to do. When you "pass an object" as a method parameter, what you're really passing is a copy of the reference that points to the object. You now have two refs pointing to the same object--one in the caller and one in the method being executed. Setting either of those refs to null does NOT affect the object itself, and does NOT affect the other ref. It just means that the ref that's been set to null no longer points to any object.
    If you want the called method to make a change that the caller can see, you need to either 1) return a value from the method, 2) encapsulate the object to be changed as a member of new class, or 3) pass the object to be changed as the single element of an array. I would STRONGLY recommend against (3) as a way to simulate pass by reference. Better to examine your design and determine whether (1) or (2) more closely matches what you're really trying to accomplish.

  • How to make an object distributed across multiple jres?

    Hi,
    We used cache data mechanism for performance tuning. It will store data in static variable (Hashtable) and get initialized when app starts . We are using IPlanet Application Server and
    Using 6 KJS engines. This object ( Hashtable) is not distributed across all JRES.It has to reinitialize data again when request goes to any other KJS.
    We avoid sharing data in session and request, as data is huge.
    Can any one help us how to make this object distributed across all KJSs?
    Thanks in advance.
    raj

    We used cache data mechanism for performance tuning.
    It will store data in static variable (Hashtable) and
    get initialized when app starts.
    We are using IPlanet Application Server and
    Using 6 KJS engines. This object ( Hashtable) is not
    distributed across all JRES. It has to reinitialize
    data again when request goes to any other KJS.
    We avoid sharing data in session and request, as data
    is huge.
    Can any one help us how to make this object
    distributed across all KJSs?When you say 'initialized when app starts' do you mean iPlanets StartUp classes, rather than the Servlets init() ? Given a 'huge' dataset, avoid the latter.
    I'd suggest that a better approach is to implement this as an Entity Bean and accessed from Session bean and using Value Objects to return the data subsets.
    Checkout the Java Pet Store
    http://java.sun.com/blueprints/code/jps13/datasheet.html

  • How to create an object within the same class???

    hi im just a newbie
    i v been always creating an object from the main class..
    but how to create an object inside the same class??
    i got main and students class
    the main got an array
    Students[] stu = new Students[]
    and i got
    stu[i] = new Students(id,name);
    i++;
    but i wanna do these things inside the Students class..
    i tried ..but i got errors.....
    how to do this
    .

    javaexpert, :)
    I really have no idea what you are trying to do since you say you've always been creating an object from the main class, yet you always want to create an object inside the same class.
    I'll assume that you have an object in the main class that you are trying to access from the Students class.
    If you are trying to access objects that are contained within the main class FROM the Students class, then know that there are two ways of doing so, one being static, and the other dynamic (look up definitions if unclear):
    1.) make the objects in the main class both static and public and access the the objects using a convention similiar to: Main.object; It's important to note that Main is the name of your main class, and object is a static object. There are better ways of doing this by using gettter/setter methods, but I'll omit that tutorial.
    2.) Create a new instance of the main class and access the objects using a similiar fashion: Main myInstance = new Main(); myInstance.myObject;
    You should really use getter and setter methods but I'll omit the code. In terms of which approach is better, step one is by far.
    I don't mean to be condecending, but you should really brush up on your programming skills before posting to this forum. This is a fundamenetal concept that you will encounter time and time again.

  • How to create an object of inner class

    hi i don't know how to create an object of an inner class..
    i got something like
    class Abc{
    private class Abcd {
    like this and i want to create an object of Abcd so that i can use some of method
    there..
    i think i should create the outter class object first right? but not sure
    the syntax.. i tried something like
    Abc.Abcd justTry = new Abc.Abcd()
    something like this..but not work..
    help me plz. ...

    If the nested class (that's not technically an inner
    class you have there) is not static, then you can't
    refer to it with OuterClassName.InnerClassName any
    more than you can refer to any other member--method
    or variable--with ClassName.staticMember.
    You need an instance.
    It's been a while since I've created an instance of a
    non-static nested class from outside that clsas, but
    I think it's something like this: Outer outer = new Outer();
    outer.Inner inner = new outer.Inner();
    Actually, I think it is this:
      Outer outer = new Outer();
      outer.Inner inner = outer.new Inner();Can't test it now though, gotta go to Taco John's for TACO TUESDAY!!!!
    Gotta love them crunchy shell bean tacos!!!

  • How to read appended objects from file with ObjectInputStream?

    Hi to everyone. I'm new to Java so my question may look really stupid to most of you but I couldn't fined a solution by myself... I wanted to make an application, something like address book that is storing information about different people. So I decided to make a class that will hold the information for each person (for example: nickname, name, e-mail, web address and so on), then using the ObjectOutputStream the information will be save to a file. If I want to add a new record for a new person I'll simply append it to the already existing file. So far so good but soon I discovered that I can not read the appended objects using ObjectInputStream.
    What I mean is that if I create new file and then in one session save several objects to it using ObjectOutputStream they all will be read with no problem by ObjectInputStream. But after that if in a new session I append new objects they won't be read. The ObjectInputStream will read the objects from the first session after that IOException will be generated and the reading will stop just before the appended objects from the second session.
    The following is just a simple test it's not actual code from the program I was talking about. Instead of objects containing different kind of information I'm using only strings here. To use the program use as arguments in the console "w" to create new file followed by the file name and the strings you want save to the file (as objects). Example: "+w TestFile.obj Thats Just A Test+". Then to read it use "r" (for reading), followed by the file name. Example "+r TestFile.obj+". As a result you'll see that all the strings that are saved in the file can be successfully read back. Then do the same: "+w TestFile.obj Thats Second Test+" and then read again "+r TestFile.obj+". What will happen is that the strings only from the first sessions will be read and the ones from the second session will not.
    I am sorry for making this that long but I couldn't explain it more simple. If someone can give me a solution I'll be happy to hear it! ^.^ I'll also be glad if someone propose different approach of the problem! Here is the code:
    import java.io.*;
    class Fio
         public static void main(String[] args)
              try
                   if (args[0].equals("w"))
                        FileOutputStream fos = new FileOutputStream(args[1], true);
                        ObjectOutputStream oos = new ObjectOutputStream(fos);
                        for (int i = 2; i < args.length ; i++)
                             oos.writeObject(args);
                        fos.close();
                   else if (args[0].equals("r"))
                        FileInputStream fis = new FileInputStream(args[1]);
                        ObjectInputStream ois = new ObjectInputStream(fis);
                        for (int i = 0; i < fis.available(); i++)
                             System.out.println((String)ois.readObject());
                        fis.close();
                   else
                        System.out.println("Wrong args!");
              catch (IndexOutOfBoundsException exc)
                   System.out.println("You must use \"w\" or \"r\" followed by the file name as args!");
              catch (IOException exc)
                   System.out.println("I/O exception appeard!");
              catch (ClassNotFoundException exc)
                   System.out.println("Can not find the needed class");

    How to read appended objects from file with ObjectInputStream? The short answer is you can't.
    The long answer is you can if you put some work into it. The general outline would be to create a file with a format that will allow the storage of multiple streams within it. If you use a RandomAccessFile, you can create a header containing the length. If you use streams, you'll have to use a block protocol. The reason for this is that I don't think ObjectInputStream is guaranteed to read the same number of bytes ObjectOutputStream writes to it (e.g., it could skip ending padding or such).
    Next, you'll need to create an object that can return more InputStream objects, one per stream written to the file.
    Not trivial, but that's how you'd do it.

  • How to persist user changes in porlet in portal

    hi,
    when i login with particular id and i made some changes
    in look and feel of portlets in portal page. can any body tell how to persist those changes for particular user in portal .
    Thanks in advance

    Sorry for the confusion. I may not have clarified my issue.
    The situation is I save UserId and Password in UserInfo JavaBean from Login Page. I can pass UserInfo to create and finder methods of BMP to connect to database. My problems is with ejbStore method. I need to find a way so that ejbStore would be able find this UserInfo object.
    Also remember Container does Activate and Passivate EJB.
    Thanks,
    Jigs

  • Client-Side Caching of Static Objects

    Hi,
    We just installed SPS12 for NWs.  I learned of this new client-side caching of static objects while reading through the release notes, and I went in to our portal to check it out.  I went to the location where the <a href="http://help.sap.com/saphelp_nw04s/helpdata/en/45/7c6336b6e5694ee10000000a155369/content.htm">release notes</a> (and an <a href="https://www.sdn.sap.com/irj/sdn/weblogs?blog=/pub/wlg/6622">article in the blog</a>) specified, System Administration > System Configuration > Knowledge Management > Content Management > Global Services.
    Problem is that I do not see Client Cache Service and Client Cache Patterns.  I enabled "Show Advanced Options," but I do not see those two configuration items.
    Does anyone know why I am not seeing those two configuration items and how I can get to those?
    Thank you.

    Hi,
    We are using SPS 12.
    KMC-CM  7.00 SP12 (1000.7.00.12.0.20070509052145) 
    KMC-BC  7.00 SP12 (1000.7.00.12.0.20070509052008) 
    CAF-KM  7.00 SP12 (1000.7.00.12.0.20070510091043) 
    KMC-COLL  7.00 SP12 (1000.7.00.12.0.20070509052223) 
    KM-KW_JIKS  7.00 SP12 (1000.7.00.12.0.20070507080500)

  • How to create good object model?

    Does anybody know how to create good object model?
    Again and again I have to create different object models in various projects. I have to solve a lot of problems.
    - Define all entities
    - Create objects for it
    - Define relations (ususlly i use SQL Databases)
    - Define methods to load/edit/save/delete entities.
    - Define methods to search and featch set of entities
    - Define events for entities (fired when it change)
    - the biggest problem is the events for collections. If i got the collection of entities for filter [FirstName = 'Sam'] i want to recieve event NewEntityAdded(), when new entity with FirstName='Sam' is created. But i want not to recieve event when that new entity's FirstName = 'Jack'.
    Do anybody know good book or set of articles for such a questions?

    Hi Facedown12,
    Does the issue resolved based on the Tatynan's suggestion? If the issue persists, please post the detail information about
    your issue, so that we can make further analysis.
    Regards,
    Katherine Xiong
    Katherine Xiong
    TechNet Community Support

  • Third-party C++ Driver : Static object

    Hello,
    I'm writting a C++ driver for Labview RT.
    I'm using Visual C++ to compile and link this driver.
    I have some initialisation problem on the target.
    It seems that static object are not created correctly. All members are not created correctly and it crashes as soon as I use these objects.
    Could someone confirm this problem ?
    Is there someone develop a C++ driver (based on VISA) for Labview RT ? Thanks for your responses !
    David Chuet

    David:
    For starters, note that NI does not officially support MSVC-built DLLs on LabVIEW RT. I believe we only officially support DLLs built with LabVIEW or CVI. However, in most cases MSVC-built DLLs will work fine.
    As to your specific question, you are correct. C++ static objects don't get initialized. Realize that the LabVIEW RT OS (Phar Lap ETS) is Win32-like. In other words, it is not 100% compatible with Win32 and MSVC, but it is extremely compatible with a large subset of the two. This is probably the biggest difference I can think of.
    My suggestion is to have static pointers to objects, then initialize them in your DLLmain. That does work and that's how we do it in NI-VISA.
    Dan Mondrik
    National Instruments

  • Static Object Vs. Lots of referece passing...

    I am implementing a discrete event simulator for which there is only ever one "executor" object and one "output manager" object used to advance time and deal with output to files. However many objects in the simulator need access to these objects and there "security" is not an issue. I was wondering if anyone knows if it is gives better performance to make these classes with static methods or whether I should pass a reference to them to nearly every other object. Also do you know why whatever one is beter?
    Cheers,
    Mark

    For this project performance really is the issue
    though. My concern is that if I pass a reference of
    an object to lots of other objects (in the order of
    100,000) that is simply a waste of time and memory
    So let's get this straight. You can have 100,000 Objects, but you can't add one reference varialble to each.
    if making the objects access methods static may
    remove this I will happily accept this over
    management and testability issues. What do you think making the method static will save you, exactly?
    What I really want to know is for example...
    is the above less effective than...No, generally , static methods are less effective than instance methods.
    if StaticObjectType in the later example is the same
    as the OtherObjectType in the first example., but
    with a static method, given that only one instance of
    OtherObjectType will ever exist. This makes no sense. There is no such thing as a 'static' Object. Static only applies to references and methods and nested classes.
    My worry is that passing this object address around
    and storing it as a field will be far less effective
    than having just a static method, although I am not
    sure this is true.There is a slight performance hit when calling an instance method over a static method. Declaring a method final may remove this. When I say slight, I mean really slight. Both methods are called in the basically the same manner.
    As this is happening thousands of times a second in
    this program and storage and speed are key really
    just need to choose the most efficient
    implementation.Again I don't understand how you can afford o have thousands of Objects but can't afford an extra reference on them.

Maybe you are looking for