Trouble understanding static objects

Hello,
I have trouble understanding static objects.
1)
class TestA
public static HashMap h = new HashMap();
So if I add to TestA.h from within a Servlet, this is not a good idea, right?
But if I just read from it, that is ok, right?
2)
class TestB
public static SimpleDateFormat df = new SimpleDateFormat();
What about TestB.df from within a Servlet? Is this ok?
example: TestB.df.format(new Date(1980, 1, 20));

There is exactly one instance of a static member for every instance of a class. It is okay to use static members in a servlet if they are final, or will not change. If they may change, it is a bad idea. Every call to a servlet launches a new thread. When there are multiple calls, there are multiple threads. If each of these threads are trying to make changes to the static memeber, or use the static memeber while changes are being made, the servelt could give incorrect results.
I hope that helped..
Thanks
Cardwell

Similar Messages

  • Trouble understanding static

    Like the topic says, I do use it (actually I have to for the GUIs or they don't compile), but I really don't understand too much about them (what they allow, what they limit) and the definition on java.sun is not very clear to me. Could someone please give me a brief explanation on this subject and maybe an example?

    public class Test {
        private String myName = "My name is . . .!";  //private variable of class Test
      public static void main(String[] argv)   //is static because the runtime environment needs to call this first, before making any objects, so it's not essential for your class, just gives you a way of running your code from within your class itself
        String theNameMainGets = "";  //main will receive the name in this
        Test testThis = new Test();  //make an instance without a name
        Test testThisWithAName = new Test("nogoodatcoding"); //pass a cool name to the constructor :D
        //theNameMainGets = whatIsMyName(); //will not work since main is static, so even though it is part of the same class, it cannot call a non-static member, whatIsMyName, because a copy of that is with every instance, and when main calls it, the instance may not exist
        theNameMainGets = testThis.whatIsMyName(); //correct way to access the non-static member, by creating an instance and then using that to access it
        System.out.println(theNameMainGets);
        theNameMainGets = testThisWithAName.whatIsMyName();
        System.out.println(theNameMainGets);
        //note, you can't say, testThis.myName; since myName is private to testThis.
    Test()
          myName = "No one named me";
    Test( String newName )
          myName = newName;
        public String whatIsMyName()
          return myName;
    }Hope this helps

  • Have Trouble understanding the runnable interface

    Hi
    I am new to java programming. I have trouble understanding threading concepts.When I run the below code,Thread3 runs first. I need a small clarification here- I created two thread objects
    Thread thread1=new Thread(new RunnableThread(),"thread1");
    Thread thread2=new Thread(new RunnableThread(),"thread2");
    As soon as I create these objects -Will the constructor with the string argument in the "RunnableThread" class gets invoked. If so why doesn't System.out.println(runner.getName()); get invoked for the above objects. what is the sequence of execution for the below program.
    /*************CODE****************************/
    class RunnableThread implements Runnable
         Thread runner;
         public RunnableThread()
         public RunnableThread(String threadName)
              runner=new Thread(this,threadName);          //Create a new Thread.
              System.out.println(runner.getName());
              runner.start();          //Start Thread
         public void run()
              //Display info about this particular Thread
              System.out.println(Thread.currentThread());
    public class RunnableExample
         public static void main(String argv[])
              Thread thread1=new Thread(new RunnableThread(),"thread1");
              Thread thread2=new Thread(new RunnableThread(),"thread2");
              RunnableThread thread3=new RunnableThread("thread3");
              //start the threads
              thread1.start();
              thread2.start();
              try
                   //delay for one second
                   Thread.currentThread().sleep(1000);
              catch (InterruptedException e)
              //Display info about the main thread
              System.out.println(Thread.currentThread());
    }

    srinivasaditya wrote:
    Hi
    I am new to java programming. I have trouble understanding threading concepts.I'd consider it to be an advanced area.
    When I run the below code,Thread3 runs first. I need a small clarification here- I created two thread objects
    Thread thread1=new Thread(new RunnableThread(),"thread1");
    Thread thread2=new Thread(new RunnableThread(),"thread2");No, this is wrong. You don't need your RunnableThread. Runnable and Thread are enough. Your wrapper offers nothing of value.
    >
    As soon as I create these objects -Will the constructor with the string argument in the "RunnableThread" class gets invoked. If so why doesn't System.out.println(runner.getName()); get invoked for the above objects. what is the sequence of execution for the below program.did you run it and see? Whatever happens, that's the truth.
    %

  • Trying to understand Static methods

    Hi all,
    I am trying to learn a little bit about static methods and hope that someone here can help me understand it better. My understanding of static methods is that they exist only once (More like global methods). This tells me that usage of static methods should be used with care as they are likely to cause problems in cases where multiple users try to access a static object at the same time.
    I am looking at a piece of code that had me thinking for a bit. I cant post the code itself but here is an example of how the code is structured
    The first class declares a couple of non static arrays and makes them available via the getters and setters. It also has one method that calls a static method in another class.
    package com.tests.statictest;
    import java.util.ArrayList;
    public class ClassA{
         ArrayList arrayList1 = new ArrayList();
         ArrayList arrayList2 = new ArrayList();
         public ClassA(){
              arrayList1.add("TEST1");
              arrayList1.add("TEST2");
              arrayList2.add("Test3");
              arrayList2.add("Test4");
         ArrayList getArrayList1(){
              return arrayList1;
         ArrayList getArrayList2(){
              return arrayList2;
         ArrayList getJoinedArrayList(){
              return ClassB.joinArrays(arrayList1,arrayList2);
    }The second class contains the static method that is called by the above class to join the two arrays. This class is used by many other classes
    package com.tests.statictest;
    import java.util.ArrayList;
    public class ClassB{
         public static ArrayList joinArrays(ArrayList list1, ArrayList list2){
              ArrayList list3 = new ArrayList();
              list1.addAll(list2);
              return list1;
    }And here is my test class
    package com.tests.statictest;
    public class ClassC{
          public static void main(String args[]){
               ClassA classA = new ClassA();
              System.out.println(classA.getArrayList1());
              System.out.println(classA.getArrayList2());
              System.out.println(classA.getJoinedArrayList());
         }The output to the above program is shown below
    [TEST1, TEST2]
    [Test3, Test4]
    [TEST1, TEST2, Test3, Test4]My question for the above is that i am wondering if the above is safe. Can you think of situations where the above is not recommended. What exactly would happen if ten instances of ClassA threads are executed at the same time? Woulnt the static method in ClassB corrupt the data?

    ziggy wrote:
    Hi all,
    I am trying to learn a little bit about static methods and hope that someone here can help me understand it better. My understanding of static methods is that they exist only once (More like global methods). This tells me that usage of static methods should be used with care as they are likely to cause problems in cases where multiple users try to access a static object at the same time. There is no such thing as a "static object" in Java. The word "static" simply means "belonging to a class as a whole, rather than an individual instance."
    My question for the above is that i am wondering if the above is safe. Can you think of situations where the above is not recommended. What exactly would happen if ten instances of ClassA threads are executed at the same time?ClassA isn't a thread, so it can't be "executed", per se.
    Woulnt the static method in ClassB corrupt the data?"Staticness" doesn't have anything to do with it; the issue at hand is operations on a shared data structure, which is a concern whether you're dealing with static or non-static members. There is nothing inherent in ClassB that will "corrupt" anything, however.
    ~

  • Trouble Understanding Logic of Primes Program

    I am reading a book called Beginning Java 7, by Ivor Horton. In his book he has a primes calculation program. The code is below. I am having trouble understanding the logic of the program. I've stared at it for the past several hours with no luck. What I can't understand is how both i and j are both initialized to 2 but the if statement:
    if(i%j == 0) {
              continue OuterLoop;                                         
            }then passes a 2 to the println() function. I am totally lost on this problem. The program below outputs all of the prime numbers from 2 to 50 without any errors. Please help!
    Thank you.
    public class Primes2 {
      public static void main(String[] args) {
        int nValues = 50;                                                  // The maximum value to be checked
        // Check all values from 2 to nValues
        OuterLoop:
        for(int i = 2 ; i <= nValues ; ++i) {
          // Try dividing by all integers from 2 to i-1
          for(int j = 2 ;  j < i ; ++j) {
            if(i%j == 0) {                                                 // This is true if j divides exactly
              continue OuterLoop;                                          // so exit the loop
          // We only get here if we have a prime
          System.out.println(i);                                           // so output the value
    }Edited by: EJP on 27/03/2013 19:54: fixed all the bizarre formatting, spelling, and removed the even more bizarre comment marketers around the text. Please use standard English and its existing conventions here.

    Hi. I did notice that. What I don't understand is how 2 is outputted as a prime number when the Net Beans debugger shows that i's value is 3 in the if statement. Where does the value 2 come from? Thanks.
    Edited by: 996440 on Mar 27, 2013 3:07 PM

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

  • Using public static object for locking thread shared resources

    Lets Consider the example,
    I have two classes
    1.  Main_Reader -- Read from file
    public  class Main_Reader
         public static object tloc=new object();
           public void Readfile(object mydocpath1)
               lock (tloc)
                   string mydocpath = (string)mydocpath1;
                   StringBuilder sb = new StringBuilder();
                   using (StreamReader sr = new StreamReader(mydocpath))
                       String line;
                       // Read and display lines from the file until the end of 
                       // the file is reached.
                       while ((line = sr.ReadLine()) != null)
                           sb.AppendLine(line);
                   string allines = sb.ToString();
    2. MainWriter -- Write the file
    public  class MainWriter
          public void Writefile(object mydocpath1)
              lock (Main_Reader.tloc)
                  string mydocpath = (string)mydocpath1;
                  // Compose a string that consists of three lines.
                  string lines = "First line.\r\nSecond line.\r\nThird line.";
                  // Write the string to a file.
                  System.IO.StreamWriter file = new System.IO.StreamWriter(mydocpath);
                  file.WriteLine(lines);
                  file.Close();
                  Thread.Sleep(10000);
    In main have instatiated two function with two threads.
     public string mydocpath = "E:\\testlist.txt";  //Here mydocpath is shared resorces
             MainWriter mwr=new MainWriter();
             Writefile wrt=new Writefile();
               private void button1_Click(object sender, EventArgs e)
                Thread t2 = new Thread(new ParameterizedThreadStart(wrt.Writefile));
                t2.Start(mydocpath);
                Thread t1 = new Thread(new ParameterizedThreadStart(mrw.Readfile));
                t1.Start(mydocpath);
                MessageBox.Show("Read kick off----------");
    For making this shared resource thread safe, i am using  a public static field,
      public static object tloc=new object();   in class Main_Reader
    My Question is ,is it a good approach.
    Because i read in one of msdn forums, "avoid locking on a public type"
    Is any other approach for making this thread safe.

    Hi ,
    Since they are easily accessed by all threads, thus you need to apply any kind of synchronization (via locks, signals, mutex, etc).
    Mutex:https://msdn.microsoft.com/en-us/library/system.threading.mutex(v=vs.110).aspx
    Thread signaling basics:http://stackoverflow.com/questions/2696052/thread-signaling-basics
    Best regards,
    Kristin
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • HT4623 I upgraded my iphone4S yesterday and Siri response with "having trouble understanding".  Is there an upgrade for Siri?

    I upgraded my iPhone4S to iOs6 and now Siri does not understand me.  Siri responses "having trouble understanding you, try again".  Is there an updgrade for Siri?  I have been searching all afternoon for a glimmer of a solution.  Any suggestions?

    Sure...
    See this Apple article for a Hard reset of a Factory reset.
    http://support.apple.com/kb/HT3728

  • Cluster and static object.

    I have application worked in cluster. Is some possibility to propagate change in static object to all application in cluster.

    You can use application context (javax.naming.InitialContext) and bind (set), rebind (set new value), lookup (get) and unbind (remove) variables (must be serializable).
    You must corect configure RMI replication.
    Changes ist propagated acros all nodes in cluster. (but unbind don't work correct - it work only locale (bug?))

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

  • Layer static objects/text on top of interactive elements

    is it possible to layer static objects/text on top of interactive elements (including scrollable slideshows or MSO) in INDD CC for DPS/Content Viewer?  The static objects (on their own layer) disappear when viewed on tablet in Content Viewer

    Thank you so much!
    Taylor Guilmette | Senior Graphic Designer
    CBRE/Grossman Retail Advisors
    33 Arch Street, 28th Floor | Boston, MA 02110
    T +1 617 912 7052 | F +1 617 912 6867
    [email protected]<mailto:[email protected]> | www.cbre.com/taylor.guilmette<http://www.cbre.com/taylor.guilmette>
    Follow CBRE/Grossman Retail Advisors: @CBREGRA<https://twitter.com/CBREGRA>

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

    If an object were static, would its non-static members act like static? What kind of problems would happen if two threads try to use this object to call one of its non-static functions? Would any member of this object (either static or non-static) be part of a critical section?

    jverd wrote:
    wpafbuser1 wrote:
    There's no such thing as a static object (since there's no instance).No, there's no such thing as a static object because the property of being static or not is not applicable to objects. Saying there's no instance is wrong, since, if there's an object, there's obviously an instance--the object.I wrote too fast, I meant there's no instantiation. Obviously there's an object/instance. But my thinking was flawed there anyway. :)
    A class is considered static when it's fields and methods are static.No. A class is static when it's a nested class and it's declared static. A class is often incorrectly called static simply by virtue of it having only static members. Regardless of whether the class is static, all instances of that class are neither satic nor non-static.The term static, incorrectly used or not, I was referring too top-level classes not inner classes.
    I guess what I'm saying is that if you include non-static methods or fields in your class, it's no longer a static class Wrong.
    class Outer {
    static class Nested {
    int x;
    void foo() {}
    }Nested has a non-static member variable and a non-static method, but it's still a static class, because it's declared static.Again, we're talking about 2 different things now.

  • 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

  • Having trouble understanding Abstract class. Help!!!!!!

    Having trouble understanding Abstract class. when is Abstract class used and for what.

    Having trouble understanding Abstract class. when is
    Abstract class used and for what.An abstract class is used to force the developer to provide a subclass, to implement the abstract methods, while still keeping the methods that were provided.
    � {�                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

Maybe you are looking for

  • Logic Pro 9 freezing and crashing at startup

    I'm running Logic Pro 9.1.5 on a MBP 15 " Mac OS X 10.6.8. It's been working perfectly for almoust a year until a couple of days ago when it suddenly crashed. After that I've been unable to run Logic Pro at all. As soon as the session has opened the

  • PreparedStatement error using VPD

    Hi all, Our team is developing an application using an Oracle DB 9.2.0.4 and BC4J 10g (9.0.5.16.0) as persistence layer. We also are using the VPD (virtual private database) to have security in the database at row level. The problem we are facing is

  • Syncserver.exe taking large amount of CPU process after iTunes closing

    Hi, OS system : Win 8.1 64 bit itune release : 12.0.1.26 Antivirus software : Kaspersky internet security 2015     release: 15.01.415 (b) After iTunes closing the syncserver.exe process will take a large amount of CPU Process. The problem has begins

  • 6230i sending and receiving txt message problems.

    I am hoping someone can help me solve this ongoing problem that i have had for over 2yrs now and i keep gettin fobbed off by o2. Ok i have a nokia 6230i and when i send txts to a particular number and them to me i am not getting them nor are they get

  • Checking for purchases on second machine

    My dad had some strange event with his WINDOWS PC (traitor...) and now it says his hard drive is having a read error (strange thing is, my PC did the same thing... I'm not a traitor though... my Mac mini can't handle parallels.) Anyways, the hard dri