Is is better to use static variables?

Hi,
Does anyone know if it's better to use static variables or to use normal variables?
Concerning the size of the code, it seems that declaring a variable as static is more consuming (for example plus 6 bytes for an object reference).
So this could mean that declaring variables as static should be avoided, but what about the execution time?
Some years ago, some javacard gurus were claiming that it's was better to use static variables (less processing required by the JVM to resolve adresses of static variables), but is it still the case?

Hi Lexdabear,
Thanks for the answer.
I did the test (I converted my all code to use static variables and methods as much as possible), and did a bench before and after, on a JCOP31 card.
The conclusion is that today JVMs and processors are much powerful than 5 years ago, and that the difference is really difficult to measure, which anyway is a good thing for us ;-)

Similar Messages

  • Using Static Variable against Context Attribute for Holding IWDView

    Dear Friends,
    I have a method which is in another DC which has a parameter of the type IWDView. In my view, I will have an action which will call the method in another component by passing the value for the view parameter. Here, I can achieve this in 2 types. One is - I declare a static variable and assign the wdDoModifyView's view as parameter value and I can pass this variable as parameter whenever calling that method or the second way - create an attribute and assign the same wdDoModifyView's view parameter as its value. Whenever I call this method, I can pass this attribute as parameter. What is the difference between these two types of holding the value since I am storing the same value i.e., wdDoModifyView's view parameter. But when I trigger the action from different user sessions, the first type of code (using static variable) prints the same value in both the sessions for view.hashCode() and View.toString(), but the same is printing the different values when I pass the attribute which holds the view parameter.
    Clarification on this is highly appreciated
    The problem I face is when I use static variable to get the view instance and export the data using the UI element's id, the data belonging to different user sessions is mixed up where as when I use Context Attribute, the same problem doesn't arise. I want to know the reason why it is so. Is there any other place or way where I can get the current view instance of each session instead of wdDoModifyView?

    Hi Sujai ,
    As you have specified the problem that we face when we use  static attributes, when end users are using the application .
    Static means i  have n number of objects but the static variable value will remain same every where.
    when it is context attribute for every object i.e nth object you have a nth context attribute i mean nth copy of the context attribute.
    so every user has a unique Iview parameter , when context is used and
    when static is used  , assume you have userA , his iview is set this intially  and u have another user B , when he is using  , since the variable is static and when you access this variable you will get the value of userA.
    Regards
    Govardan Raj

  • When should I use static variable and when should not? Java essential

    When should I use static variable and when should not? Java essential

    Static => same value for all instances of the class.
    Non-static => each instance can have its own value.
    Which you need in which circumstances is completely up to you.

  • Can I use static variable in EJB?

    Many books suggest developer don't use static variable in EJB,I want to know why?
    I know there isn't any problem if the static varibale is read only
    For writable static varible ,what will happen if I use a static Hashtable for share data
    Help me!Thank you very much!!

    Greetings,
    I know that "EJB business methods are not allowed to
    block on synchronized resources" Just where do you "know" that from?? The EJB 2.0 Specification, at least, is nowhere in agrement with this statement. If it comes from a book I would question the author's reasoning. Contractually, there's no sound basis for this. In the case of Session Beans, they have an expressedly direct and single-threaded association with a client. From a design viewpoint, it certainly seems unnecessary for a bean to "block" its one-and-only client, but to say that it "is not allowed to" do so is without merit. Entity Beans, on the other hand, are concurrently accessible. Yet, with regard to a transactional context being in effect, the container does indeed block on a bean's business methods. For the bean to do so itself is, therefore, unnecessary. Furthermore, the specification explicitly concedes that a "Bean Provider is typically an application domain expert" and "is not required to be an expert at system-level programming." (EJB 2.0 Spec. 3.1.1) From these statements alone it is reasonable to assume the above statement is meritless since the Bean Provider is not expected to even consider synchronization issues when developing a bean.
    But I'm mixed up why we could use "Hashtable" or otherApparently, because your sources are as well...
    collection classes in the EJB ,in these method many
    methods are synchronized In fact, not only "can we use" them but, with respect to multiple-row finders in Entity Beans we are [i]required to use them (or an iteration of them)! Not all Collection classes are synchronized (so called "heavy-weight collections"). As shown above, that the choice of a particular Collection class might be synchronized is of little consequence since a bean designed under strict adherence to the specification ensures that it is never concurrently writeable.
    Could someone provide a good way for this problem?
    Please Help Me!!!Regards,
    Tony "Vee Schade" Cook

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

  • I want to use static variable instead of using variable in servlet context

    Hi all,
    In my web application i have to generate a unique Id.
    For this, At the application startup time i am connecting to the database and getting the Id and placing it in the servlet context.
    Every time i am incrementing this id to generate a unique id.
    But, now i want to place this id in a static variable which is available to all the classes.
    why i want to do this is to reduce burden on servlet context.
    my questing is, is this a best practice ? If not please give me your valuable suggestion.
    thanks
    tiru

    There isn't a problem with this as long as you want to share the value of that variable with all requests. If this is read-only except when it is first set then you're fine. The only real issue will be how to initialize and/or reinitialize the variable. When the servlet is started, how will you get the value for the variable? If the servlet is shutdown and restarted (a possibility in any application server) how will you re-read the variable? You need to answer these questions to decide the best route. It may be as simple as a static initializer or it may be more complex like a synchronized method that is called to see if the variable is set.

  • Using static variables in ejb

    I'm interested in the rule from the EJB spec:
    � An enterprise bean must not use read/write static fields. Using read-only static fields is
    allowed. Therefore, it is recommended that all static fields in the enterprise bean class be
    declared as final.
    This rule is required to ensure consistent runtime semantics because while some EJB containers may
    use a single JVM to execute all enterprise bean�s instances, others may distribute the instances across
    multiple JVMs.
    question 1
    Can you call "Math.random();" in ejb code???
    The javadoc for this method says
    When this method is first called, it creates a single new
    * pseudorandom-number generator
    This means that you can't use it right?
    This is not a problem for me, I know that you can go (new Random()).nextDouble();
    What I'm interested in is, does the EJB spec permit use of this method, and how are you supposed to know when you're breaking the spec like this.
    question 2:
    how about if you have a class
    class MyClass{
    public static final ArrayList MY_LIST = new Arraylist();
    Surely you can't read and write to MY_LIST from EJB's cause you're breaking the rule.
    But at what point are you actually breaking the rule?
    Can anyone out there spell this out for me??

    � An enterprise bean must not use read/write static fields. Using read-only static fields is
    allowed. Therefore, it is recommended that all static fields in the enterprise bean class be
    declared as final.
    Note that the rule covers usage of ALL static fields, not just fields on the implementation class.
    If I use
    MYBeanStaticVariableHolder.myStaticVariable
    for read/write.
    I understand that it's not a good idea, and I would never do it.
    But, does it actually break the spec. yes or no!!! - YES
    If yes, then fine I'm happy, what about my Math.random() question?
    Can you call "Math.random();" in ejb code???
    Math.random() is effectively read-only, because you never write to the result returned and therefore does not break the rule, so calling Math.random() would be allowed.
    how about if you have a class
    class MyClass{
    public static final ArrayList MY_LIST = new Arraylist();
    Surely you can't read and write to MY_LIST from EJB's cause you're breaking the rule.
    But at what point are you actually breaking the rule?
    Can anyone out there spell this out for me??
    If you write to a static field, update the state of an object in a static field, or update the state of an object returned by a static method, when the method does not return a unique instance at each invocation, you are breaking the spec
    public class Sample
        public static final int START_MODE = 0;    // OK
        public static final int STOP_MODE = 1;      // OK
        public static int DEFAULT_MODE;           // updating this is BAD
        private int currentMode;
        public int getMode(){ return currentMode; }
        public void setMode(int mode){ currentMode = mode; }
        // Updating instance is BAD
        public static Sample instance = null;
        // Updating returned instance is BAD
        public synchronized static getInstance()
            if( instance == null ) instance = new Sample();
            return instance;
        // Updating returned instance is OK
        public synchronized static getUniqueInstance()
            Sample instance = new Sample();
            instance.setMode(Sample.MODE_START);
            return new Sample();
    }Hope that helps.

  • Using static variable in orchestration for each message

    Once a file is dropped to our Biztalk server I am capturing data from each message. However, I need to assign a batchID for this file that I will write to the database along with the data. How do I build my orchestration so that the code I'm using to generate
    the BatchID doesn't create a new ID for each message? I want each message to use the same ID.
    Thanks.
    Raymond

    Shankycheil,
    I think you've pointed out my primary issue. I'm fairly new to Biztalk and I just kind of let it do its thing when it comes to EDI processing. So, I guess my issue is due to the fact that I'm letting the EDI Disassembler debatch the file and pass messages
    into the orch one at a time. I have code in an expression shape that generates a BatchID, but of course if I'm debatching it creates a new BatchID for each message. How do I deal with the file as a whole inside the orchestration so that once I generate a BatchID
    it uses it for all of the messages in file? I've done what Prabhdeep suggested and promoted a field in the schema so that I can set the BatchID, but it needs to be the same for each message in a file.
    Thanks.
    Raymond

  • Using static variables in JSP

    Hi All,
    I have written the following code, but its not compiling saying that "Class or interface declaration expected. static "
    I dotn know whats wrong in this scriplet though.. any help is greatly appretiated.
    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>JSP Scriplet</title>
    </head>
    <body>
    <%
    static int counter = 15;
    for(int i = 0; i < 15; i++){
    int p = returnCounter();
    if(p == 0)
    System.out.println("I am the 15th user");
    public static int returnCounter(){
    counter = counter - 1;
    System.out.println("counter : " + counter);
    return counter;
    %>
    </body>
    </html>

    Simply put, you're Java code is wrong.
    The detail is that essentially all of the code in your JSP file is in one big method.
    So, here's what your code looks like to the compiler:
    public void _internalJspDoPageCode() {
        static int counter = 15;
        public static int returnCounter() {
    }You can't simply nest methods like this in Java.
    If you want to, you can try this:
    <%
        public class mycounter {
            static int counter = 15;
            public static int returnCounter() {
                counter = counter - 1;
                return counter;
        for (int i = 0; i < 15; i++) {
            int p = mycounter.returnCounter();
            if(p == 0)
                System.out.println("I am the 15th user");
    %>That will create an inner class with a static member, which is basically what you're trying to do.
    But note that this inner class is only accessible from this JSP page, and no where else.

  • Using global variable read status

    Hi Experts,
    I need to change the Note based o the Service Ticket status. I declared global variable as a string in ZL_ICCMP_BT_BTSHEADER_IMPL (Component: ICCMP_BTSHEAD; View: BTSHeader)
    And I am passing the Status to this global variable using the GET and SET methods of the STRUCT.ACT_STATUS attribute in BTSTATUSH node in same component and view.
    I referred this global variable in DO_PREPARE_OUTPUT of the component ICCMP_BTTEXT/TextView to set the Note as shown below.
    if ZL_ICCMP_BT_BTSHEADER_IMPL=>GC_STATUS = 'E0001'.
    I would like to know whether this approach is the best way to read status or any other optimistic  approach is there to follow for my this scenario. Please advise me.
    Thanks
    Chand

    Hi Basha,
    If you are using static variables, i wouldn't recommend using this approach.. there are better approach to get/set values in web client session which avoids setting/clearing static variables etc..
    you can follow below approach..
    1. To Get/set the variable in ic session to avoid the static variable.. for eg global cuco is available which you can use for this purpose.
    lr_bdc type ref to if_crm_ui_data_context.
    lr_bdc = cl_crm_ui_data_context_srv=>get_instance( me ).
    check lr_bdc is bound.
    Using SET_DATA_ATTRIBUTE set the attribute value and using GET_DATA_ATTRIBUTE get the attribute valueu2026get_attribute, set_attribute
    read current BuAg if exist
    lr_buag ?= lr_bdc->GET_DATA_ATTRIBUTE( 'CURRENTBUAG' ).
    Here "CURRENTBUAG" is the attribute name, you can give any attribute name while setting and get the same attribute value via get_data_attribute.
    Cheers,
    Sumit Mittal

  • Global static variable. I just CANNOT get global for everything

    Hi,
    I copied a connection pool example from oracle web site. It uses static variable. Its not a servlet, its a javabean. I can run a million times in one session and everything is great. If I open up another session, it creates another instance and creates more connections when it should be seeing the previous instance.
    My question is how to make a static variable global to the entire application? Do i have to initialize it in the servlet container? All im doing is calling a JSP page which calls this bean. If instance is null, create 5 new connections. Well like i stated above, it works for a single session. It appears that each session gets its own instance. I have been working and debugging this for a long time and I just cannot come up with a solution...
    Any ideas???
    Thanks as always

    Declar it as static within the servlet class.
    public class MyServlet extends HttpServlet {
    public static ConnectionPool pool;
    Then you can access it from any JSP/Servlet using MyServlet.pool but you may have to import the class into the JSP/Servlet.
    Be aware that there may be synchroniztion issues when you access this static object so you may want to synchronize access to the pool.
      synchronized (application) {
           if (MyServlet.pool == null) { //initialize pool code here }

  • Static variable in servlet

    Is it safe to use static variable in servlet in weblogic if clustering is
              not being used? Thanks.
              Leo
              

    Is it safe to use static variable in servlet in weblogic if clustering is
              not being used? Thanks.
              Leo
              

  • Where to put init code for static variables? (for UIImages)

    I know that static variables are sorta a global, is that how UIImage is usually stored? What is the convention to declare UIImage variables that exists throughout the lifetime of the app? Where is a good place to init it if I choose to use static variables?

    OK, in that case do something like this:
    MyClass.m
    #import "MyClass.h"
    static UIImage *classImage;
    @implementation MyClass {
    + (void)initialize {
    classImage = <whatever to load image>;
    Code like the above makes the 'classImage' variable work like a typical class variable. It is available to all instances of MyClass but is not visible to other classes. Like a 'private static' class variable in Java. Nothing goes in the header for this variable.
    The 'initialize' method is called once the first time anything ever references MyClass. Kind of like a static initializer in Java. Notice the use of '+' instead of '-' for the method. The '+' makes it a class method instead of an instance method.
    Does that help?
    Message was edited by: RickMaddy

  • BPEL and Static variables

    Hi all,
    does anyone know how to define/use static variables inside a BPEL process? Or, is there any way so I can keep data from a (synchroneous) invocation to be used during the next (synchroneous) invocation?
    thanks for your help, I have been working on this for many many days !
    Abdel.

    How about a BPEL process that maintains your static variables and uses a custom correlation token. Queries to the process can retrieve the variable requested, and if they use the custom correlation token then the process will act as a singleton.
    I suggest using event processing rather than simple receive to handle the messages.

  • Static variables in CLR stored procedures

    Is there really no way to use static variables shared by several CLS stored procedures in the same DLL, except by making them read only?
    Or can you add new server variables and read/write those from CLR stored procedures without having to open a connection and run a query each time you need a value?
    In my SP's, I would like to know the path where the database's .mdf file is stored on disk (not to access that file, but to store other files in a location that's always the same relative to the database).
    I thought I had found the solution last week, after some digging through sites like stackoverflow: make it a static read-only variable, and initialize it through a function call when the module is loaded.  The CLR will "forget" that it is
    read only at that time.
    For some reason this has worked perfectly for a week, but today it suddenly started failing -- without any code change or even a recompile, it started after a simple reboot of the test machine.
    The code (just the relevant lines, in VB syntax):
    Private Shared ReadOnly Datapath As String = InitDataPath()
    Private Shared Function InitDataPath() As String
    Try
    Using cn As New SqlConnection("context connection=true"),
    cmd As New SqlCommand("SELECT TOP 1 [physical_name] FROM sys.database_files WHERE type=0", cn)
    cn.Open()
    The "cn.open" line throws "Data access is not allowed in this context."
    It did not yet do that yesterday, and the day before, and all the way back to January 6th, when I wrote that piece of code.  The DLL hadn't even been recompiled since then, I was working on the application that uses the database and the stored procedures.

    I think I found it, at least it works again -- I just hope it's for more than a week now.
    Declare assembly as unsafe when installing it in SQL server (it was already 'EXTERNAL_ACCESS' for file I/O, but non-read-only static variables require UNSAFE).
    I initialize the static variables to 'Nothing' (NULL for C# users), and instead of finding the path when the module is loaded, I added a line 'if xxx is nothing then init()' at the start of each procedure / function. Init() is a a simple initialization
    routine that initializes the static variables upon first access.
    added SystemDataAccess:=DataAccessKind.Read to the declaration of UDF's (not possible and not necessary for procedures, apparently, but if what caused the assembly to load was a function, it would still fail).

Maybe you are looking for

  • How to implement a tree like security realm?

    hi all: i am working on a project . it's a very complex one and most importantly there's so many functions( 1000 or more) and every fuction should be protected resources. so i have to define many roles and map the roles to the many functions. it's a

  • Logout works fine on Local Machine but not on Server

    I have the following code in my backing bean:       ExternalContext external =         FacesContext.getCurrentInstance().getExternalContext();       HttpSession session = (HttpSession) external.getSession(false);       session.invalidate();      // r

  • APEX4: Validation failure. Is this a bug?

    Below is an extract of the debug output. P610_ORD is a database column text field. I have tried deleting the validation and item and recreating them. Short of deleting the page and starting again I have no idea what to do! Any suggestions. 0.06200 0.

  • FS10N vs FBL3N

    Dear Friends, when i am checking FBL3N and FS10N for a particualr businees area it shows some difference. what may the reason for this difference ? Thanks in advance

  • I have old photoshop elements 5, want to buy new version.

    If I install new software will photo collections be shown in new software? do I have to tag each photo again? or can I import back up catalogue from old version to set up collections? answer will be great, thank youalso is there any advantage in buyi