Can a object created using static keyword be recreated? Singleton Pattern

Hi All
To implement a Singleton I can use the following code
public Singleton {
private Singleton(){
private static final s_instance = new Singleton();
public Singleton getInstance(){
return s_instance;
Now if the Class Singleton gets unloaded during a program execution and again get loaded won't s_instance be recreated? If my question is correct this would lead to be leading to a new Singleton class instance with all the original variables.
Having answered the above question if I lazily initialize my Singleton using the following code won't the above problem still occur.
public Singleton {
private Singleton(){}
private final volatile Singleton s_instance = null;
public Singleton () {
if(s_instance != null) {
synchronized (s_instance) {
s_instance = new Singleton();
return s_instance;
Having answered all the above questions what is the best way to write a Singleton?

Would the class get unloaded even if the Singleton object has some valid/reachable references pointing to it?
On a different note, will all the objects/instances of a class get destroyed if the class gets unloaded.That's the other way round, really: instances cannot be garbage-collected as long as they are strongly reachable (at least one reference pointing to them), and classes cannot be unloaded as long as such an instance exists.
To support tschodt's point, see the JVM specifications: http://java.sun.com/docs/books/jvms/second_edition/html/Concepts.doc.html#32202
*2.17.8 Unloading of Classes and Interfaces*
A class or interface may be unloaded if and only if its class loader is unreachable. The bootstrap class loader is always reachable; as a result, system classes may never be unloaded.
Will the same case (Custom ClassLoader getting unloaded) occur if I write the singleton using the code wherein we lazily initialize the Singleton (and actually create a Singleton instance rather than it being a Class/static variable).You should check the meaning of this vocabulary ("object", "instance", "reference"): http://download.oracle.com/javase/tutorial/java/javaOO/summaryclasses.html
The difference between the lazy vs eager initializations is the time when an instance is created. Once it is created, it will not be garbage collected as long as it is reachable.
Now I'm wondering, whether being referenced by a static attribute of a class guarantees being reachabe. I'm afraid not (see the JLS definition of reachable: http://java.sun.com/docs/books/jls/third_edition/html/execution.html#44762). That is, again, unless the class has been loaded by the system class loader.

Similar Messages

  • "requires unreachable" warning emitted when using static variables and the singleton pattern

    I'm implementing code contracts on an existing code base and I've come across this situation in a few places. Wherever we have additional logic with code contracts where a singleton instance is instantiated, all code contracts emit a "reference use
    unreached", or "requires unreachable" warning.
    The code below demonstrates this.
    static string instance = null;
    static string InstanceGetter()
    if (instance == null)
    instance = "initialized";
    AdditionalLogic(instance); // requires unreachable warning on this line
    return instance;
    static void AdditionalLogic(string str)
    Contract.Requires(str != null);
    Console.WriteLine(str);

    Would the class get unloaded even if the Singleton object has some valid/reachable references pointing to it?
    On a different note, will all the objects/instances of a class get destroyed if the class gets unloaded.That's the other way round, really: instances cannot be garbage-collected as long as they are strongly reachable (at least one reference pointing to them), and classes cannot be unloaded as long as such an instance exists.
    To support tschodt's point, see the JVM specifications: http://java.sun.com/docs/books/jvms/second_edition/html/Concepts.doc.html#32202
    *2.17.8 Unloading of Classes and Interfaces*
    A class or interface may be unloaded if and only if its class loader is unreachable. The bootstrap class loader is always reachable; as a result, system classes may never be unloaded.
    Will the same case (Custom ClassLoader getting unloaded) occur if I write the singleton using the code wherein we lazily initialize the Singleton (and actually create a Singleton instance rather than it being a Class/static variable).You should check the meaning of this vocabulary ("object", "instance", "reference"): http://download.oracle.com/javase/tutorial/java/javaOO/summaryclasses.html
    The difference between the lazy vs eager initializations is the time when an instance is created. Once it is created, it will not be garbage collected as long as it is reachable.
    Now I'm wondering, whether being referenced by a static attribute of a class guarantees being reachabe. I'm afraid not (see the JLS definition of reachable: http://java.sun.com/docs/books/jls/third_edition/html/execution.html#44762). That is, again, unless the class has been loaded by the system class loader.

  • Can sprites be created using Lingo?

    Can be created using Lingo dynamically? Which
    function?

    the functions mentioned by Mike are new ones, added just to
    make things more user friendly (user friendly ??).
    You just have to set the 'puppet' property of any sprite
    channel (provided your movie has that many number of channels) and
    you can control the sprite using script (even the blank ones).
    you can even remove these puppeted sprites by just setting
    the property to false, and setting the member to "".

  • Clean up of objects created using NewObject()

    Hello
    I've just started playing around with JNI in order to create a Java API layer on top of an existing C++ library. I figured out how to create an instance of a Java class in native code using env->NewObject() method. My question is who takes care of cleaning up this object? Is it my responsibility ?
    jclass cl = env->FindClass("MyJavaClass");
    jmethodID ctorId = env->GetMethodID(cl, "<init>", "()V");
    jobject obj = env->NewObject(cl, ctorId);
    // set member field (int)
    jfieldID fid = env->GetFieldID(cl, "i", "I");
    env->SetIntField(obj, fid, 5);
    // set member field (string)
    fid = env->GetFieldID(cl, "buffer", "Ljava/lang/String;");
    jstring jstr = env->NewStringUTF("hello from cpp");
    env->SetObjectField(obj, fid, jstr);
    // return object back to Java
    return obj;Thanks
    Amit

    See the [JNI Reference|http://java.sun.com/j2se/1.5.0/docs/guide/jni/spec/design.html#wp529], section 'Implementing local references'.
    Notes:
    (a) If you are constructing an object to return to the Java code obviously you don't want to free it yourself.
    (b) Anything you construct inside a JNI method apart from the return value and anything reachable from it can be released by the JVM when the JNI method returns.
    (c) You can use DeleteLocalRef() or Push/PopLocalFrame() to manage objects you create yourself if you like, but unless you do large amounts of object creation, or you have callbacks into Java code, it's not really necessary.
    (d) All this also applies to references that you acquire via JNI calls (e.g. jclass references).
    (e) Another thing often overlooked is that the result of GetStringChars() or GetStringUTFChars() also needs to be released, with ReleaseStringChars() or ReleaseStringUTFChars().

  • Can barcodes be created using Report Builder

    Hi Gurus,
    Can anybody please tell me How to create Barcodes using Oracle..
    It's Urgent..
    Please Help..
    Regards
    Swati

    Dear.......
    yes of course, u will purchase the Bar code machine fom market, then u when u keep near to barcode and press the button then the corresponding number or data will be pase in your screen where at this time ur cursor is blinking, either in MS word or in oracle forms.
    thx.

  • Serialazation of objects created using jaxb

    I am using jaxb to create java classes from a dtd. Problem is that I am not able to serialize these objects. We are using JMS queues and want to compare the cost (performance) of marshal/unmarshal and serialize/deserialize of these objects. Jaxb faq provides a example http://java.sun.com/xml/jaxb/CheckbookBalance.java but it uses marshal and unmarshal methods to do serialization. I have tried changing the classes generated by jaxb to implement serializable but i get runtime "Object couldnot be serialized" exception. Is there any way to make the objects of classes generated by jaxb serializable?
    Thanks,
    -Rakesh

    IMHO these classes are not meant to be serialised, the XML produced is the medium that is tranmitted between programs. The XMLB classes are available at both ends to do the marshalling/unmarshalling.I dissagree, xml is just an interface to the outside world, so to speak. I'm working with a project that uses jini and rmi, I really don't need the extra hasle of writting custom serialization classes.

  • What is difference when using import statement with static keyword ?

    10. package com.sun.scjp;
    11. public class Geodetics {
    12. public static final double DIAMETER = 12756.32; // kilometers
    13. }
    Which two correctly access the DIAMETER member of the Geodetics class? (Choose two.)
    A. import com.sun.scjp.Geodetics;
    public class TerraCarta {
    public double halfway()
    { return Geodetics.DIAMETER/2.0; }
    B. import static com.sun.scjp.Geodetics;
    public class TerraCarta{
    public double halfway() { return DIAMETER/2.0; } }
    C. import static com.sun.scjp.Geodetics.*;
    public class TerraCarta {
    public double halfway() { return DIAMETER/2.0; } }
    D. package com.sun.scjp;
    public class TerraCarta {
    public double halfway() { return DIAMETER/2.0; } }
    The correct answer is A,C.I understood how A is the answer ,but can anyone explain me about package import using static keyword.The above example can be used as a reference.
    Thanks for your consideration.

    amtidumpti wrote:
    10. package com.sun.scjp;
    11. public class Geodetics {
    12. public static final double DIAMETER = 12756.32; // kilometers
    13. }
    Which two correctly access the DIAMETER member of the Geodetics class? (Choose two.)
    A. import com.sun.scjp.Geodetics;
    public class TerraCarta {
    public double halfway()
    { return Geodetics.DIAMETER/2.0; }
    B. import static com.sun.scjp.Geodetics;
    public class TerraCarta{
    public double halfway() { return DIAMETER/2.0; } }
    C. import static com.sun.scjp.Geodetics.*;
    public class TerraCarta {
    public double halfway() { return DIAMETER/2.0; } }
    D. package com.sun.scjp;
    public class TerraCarta {
    public double halfway() { return DIAMETER/2.0; } }
    The correct answer is A,C.I understood how A is the answer ,but can anyone explain me about package import using static keyword.The above example can be used as a reference.
    Thanks for your consideration.here's a link to a small tutorial:
    [http://www.deitel.com/articles/java_tutorials/20060211/index.html]

  • Exporting 3D Objects for use in Photoshop

    As Photoshop CS3 has the ability to handle 3D layers and Illustrator CS3 has the ability the create 3D objects i do not see any reason why there is no possibility in Illustrator to Export the 3D objects that then can be used in Photoshop. It would be a very appreciated feature.
    Andreas

    > I happen to know for sure that the plug-in does create a 3D model...
    How do you know this? While I Don't know for sure that it doesn't I strongly doubt that it would. The object created using the effect is merely a 2D object extruded to add the illusion of depth. A true 3D model contains far more information, such as features on all sides. Since Illustrator is only a 2D drawing program, there's no need for it to support 3D modeling, so no need for the programmers to spend time storing 3D data in the database of object data.
    So, if you "know for sure" that the plug-in created a 3D model, how do you know this? Can you link to some proof?

  • Problem with static keyword

    I faced Problem while using static keyword in Netbeans 6.5

    'static' doesn't exist anymore in JavaFX Script. Instead, put your functions and variable definitions outside of your class. Then they will be script level, which is roughly equivalent to 'static' in Java.

  • Singleton pattern class and static class

    Hi,
    what is difference between the singleton pattern class and static class ?
    in singleton pattern, we declare a static member[which hold one value at a time] ,static method[ which return static member value] and a private constructor[not allow to direct instantiation]. My words are -- as a singleton pattern we implement static class .
    so can we say a singleton pattern is static class it means both are same or is any difference between these two ??

    malcolmmc wrote:
    On several occasions I've had to convert a static (never instanceated) class to a singleton type, for example because I realise I need an instance per thread, or I decide to make a program more modular, with more than one configuration.
    I've never done the opposite.
    So generally I favour the singleton if there any "state" involved, because it's more flexible in unanticipated directions. It also gives extra flexibility when building tests, especially if you program to an interface.Total agreement; if anything it is dead hard to override static method logic with mock code in unit tests (I had to do it by keeping the static methods in place but making them internally use a singleton instance of itself of which the instance variable could be overwritten with a mock implementation for unit testing purposes...).
    'Static classes' and/or methods are great for very simple util functions, but I wouldn't use them for anything other than that.

  • Creating  a static method returning Logger Object inside class

    Hello,
    Instead of creating Logger Instance in every class , can i do like this way by creating a static method in some class returning a Logger object , and using that method for getting instance of Logger in another class through that method
    Regards
    Mayur Mitkari

    On a related note, if you want to make it simpler, never do this:
    if (a == true)Instead, just do if (a)It's pointless and cluttersome to use == or != with true or false.
    // wrong
    if (a == true)
    if (a != false)
    // right
    if (a)
    // wrong
    if (a == false)
    if (a != true)
    // right
    if (!a)Also, note that
    if (x) {
      return true;
    else {
      return false;
    }can be simplified to return x;If you do that and change your variable to something a bit more meaningful, like trueCount or numTrue or something, your code would be
    int trueCount = 0;
    if (a) trueCount++;
    if (b) trueCount++;
    if (c) trueCount++;
    return trueCount >= 2;which is about as simple and clear as it can get, IMHO. Using less code doesn't necessarily make the code simpler or clearer. The idea is that someone reading the code can easily understand what it does.
    And note that the above can be easily generalized to "Are there at least M true values in this array/list of N booleans?" and still be concise and clear.

  • How to use Workbench created Thesaurus and Keyword redirects in Endeca 3.1.2?

    Hi ,
    I have been trying to add a few Keyword Redirects and Thesaurus entries in the Endeca Workbench. After I add them, I am unable to see either the Keyword Redirects or Thesaurus being reflected in the Authoring/Live dgraphs!
    I assumed that workbench entries will automatically override/merge the dev studio files when I run a baseline update. (There were no Keyword Redirects and Thesaurus entries I had created at this point through dev. studio.
    But, When I add them via the Developer studio and run a baseline update, I am able to verify their working in jspref as well as in the Production site. PFB the version of Endeca that I am using:
    PlatformServices – 6.1.3
    WorkBench – 3.1.2
    MDEX – 6.4.1
    CAS – 3.1.2
    I want to know how I can have workbench created/managed Keyword Redirects and Thesaurus.
    I tried creating the Keyword Redirects and Thesaurus entries first (in the workbench) and then running a baseline update and vice versa, both the approaches didn't seem to work.
    I have used the OOTB ProductCatalogIntegration set up to deploy this application and I've not changed anything in the AppConfig.xml either.
    Any help would be hugely appreciated as I have been trying to acheive this for a long time without any progress.
    Please let me know if you have any ideas on how to resolve this.
    Thanks in advance,
    Arjun

    I was able to get the thesaurus working by just adding the entries in the Workbench. There was a problem with the IFCR Utility which was the reason why the Thesaurus entries were not being published to the Live Dgraphs. Once that was fixed, the thesaurus worked correctly.
    But Keyword Redirects had more effort as our site was using presentation API. The keyword directs configured in the workbench are not being returned as Supplement Objects, but rather as a content XML. So we needed to handle the XML content which contains the redirect url.
    If you have set up your application correctly, then you should be able to see the redirects in jspref atleast.

  • Can Adobe Muse be used to create database driven websites?

    Can Adobe Muse be used to create database driven websites, or is it only through "replace image through browse from your computer".

    Hi Edgard,
    I am afraid that this is not possible in Muse at this stage, I will recommend that you post this on our ideas section over here, Ideas for features in Adobe Muse, and let our devs team know of this requirement.
    In muse you can only design static content. For any dynamic content that you need to render via DB, you will need to write custom code and insert it in Muse via 'object -> insert html' option or 'properties -> metadata -> html for head' option.
    - Abhishek Maurya

  • Can commenting tools be used for a PDF document created by scanning another document?

    I have Adobe Reader X.  It has commenting tools.  I
    created a PDF file by scanning another docu
    ment (a newpaper clipping) to the PDF file for an attachment to an Email. I am not able to use the highlighting tool on the new PDF document.  Since I was the author of the PDF document in this case (but obviously did not use Adobe Acrobat to create it), can I somehow enable use of commenting tools for the document?

    The highlight tool works for highlighting text that is in the document (as text objects). Images of text, which is what you get with a scan, cannot be highlighted with this tool, even if you had Acrobat.

  • Use of 'static' keyword in synchronized methods. Does it ease concurrency?

    Friends,
    I have a query regarding the use of 'synchronized' keyword in a programme. This is mainly to check if there's any difference in the use of 'static' keyword for synchronized methods. By default we cannot call two synchronized methods from a programme at the same time. For example, in 'Program1', I am calling two methods, 'display()' and 'update()' both of them are synchronized and the flow is first, 'display()' is called and only when display method exits, it calls the 'update()' method.
    But, things seem different, when I added 'static' keyword for 'update()' method as can be seen from 'Program2'. Here, instead of waiting for 'display()' method to finish, 'update()' method is called during the execution of 'display()' method. You can check the output to see the difference.
    Does it mean, 'static' keyword has anything to do with synchronizaton?
    Appreciate your valuable comments.
    1. Program1
    public class SynchTest {
         public synchronized void display() {
              try {
                   System.out.println("start display:");
                   Thread.sleep(7000);
                   System.out.println("end display:");
              } catch (InterruptedException e) {
                   e.printStackTrace();
         public synchronized void update() {
              try {
                   System.out.println("start update:");
                   Thread.sleep(2000);
                   System.out.println("end update:");
              } catch (InterruptedException e) {
                   e.printStackTrace();
         public static void main(String[] args) {
              System.out.println("Synchronized methods test:");
              final SynchTest synchtest = new SynchTest();
              new Thread(new Runnable() {
                   public void run() {
                        synchtest.display();
              }).start();
              new Thread(new Runnable() {
                   public void run() {
                        synchtest.update();
              }).start();
    Output:
    Synchronized methods test:
    start display:
    end display:
    start update:
    end update:
    2. Program2
    package camel.java.thread;
    public class SynchTest {
         public synchronized void display() {
              try {
                   System.out.println("start display:");
                   Thread.sleep(7000);
                   System.out.println("end display:");
              } catch (InterruptedException e) {
                   e.printStackTrace();
         public static synchronized void update() {
              try {
                   System.out.println("start update:");
                   Thread.sleep(2000);
                   System.out.println("end update:");
              } catch (InterruptedException e) {
                   e.printStackTrace();
         public static void main(String[] args) {
              System.out.println("Synchronized methods test:");
              final SynchTest synchtest = new SynchTest();
              new Thread(new Runnable() {
                   public void run() {
                        synchtest.display();
              }).start();
              new Thread(new Runnable() {
                   public void run() {
                        synchtest.update();
              }).start();
    Output:
    Synchronized methods test:
    start display:
    start update:end update:
    end display:

    the synchronized method obtain the lock from the current instance while static synchronized method obtain the lock from the class
    Below is some code for u to have better understanding
    package facado.collab;
    public class TestSync {
         public synchronized void add() {
              System.out.println("TestSync.add()");
              try {
                   Thread.sleep(2000);
              } catch (InterruptedException e) {
                   e.printStackTrace();
              System.out.println("TestSync.add() - end");          
         public synchronized void update() {
              System.out.println("TestSync.update()");
              try {
                   Thread.sleep(2000);
              } catch (InterruptedException e) {
                   e.printStackTrace();
              System.out.println("TestSync.update() - end");          
         public static synchronized void staticAdd() {
              System.out.println("TestSync.staticAdd()");
              try {
                   Thread.sleep(2000);
              } catch (InterruptedException e) {
                   e.printStackTrace();
              System.out.println("TestSync.staticAdd() - end");
         public static synchronized void staticUpdate() {
              System.out.println("TestSync.staticUpdate()");
              try {
                   Thread.sleep(2000);
              } catch (InterruptedException e) {
                   e.printStackTrace();
              System.out.println("TestSync.staticUpdate() - end");
         public static void main(String[] args) {
              final TestSync sync1 = new TestSync();
              final TestSync sync2 = new TestSync();
              new Thread(new Runnable(){
                   public void run() {
                        sync1.add();
              }).start();
              new Thread(new Runnable(){
                   public void run() {
                        sync2.update();
              }).start();
              try {
                   Thread.sleep(3000);
              } catch (InterruptedException e) {
                   e.printStackTrace();
              new Thread(new Runnable(){
                   public void run() {
                        sync1.staticAdd();
              }).start();
              new Thread(new Runnable(){
                   public void run() {
                        sync2.staticUpdate();
              }).start();
    }

Maybe you are looking for