Static function behaviour...

what happns when a static function is used from several classes simultaneously,,,,,,...
will it be multithreaded or synchronized or will it become unstable

Potentially, just like an object field used in a regular non-synchronized method. Ordinary local variables are fine, though.
Think of static methods and variables as being attached to the Class object instead of an object instance.

Similar Messages

  • Can not call a static function with-in a instance of the object.

    Another FYI.
    I wanted to keep all of the "option" input parameters values for a new object that
    i am creating in one place. I thought that the easiest way would be to use a
    static function that returns a value; one function for each option value.
    I was looking for a way to define "constants" that are not stored in
    the persistent data of the object, but could be reference each time
    the object is used.
    After creating the static functions in both the "type" and "body" components,
    I created the method that acutally receives the option input values.
    In this method I used a "case" statement. I tested the input parameter
    value, which should be one of the option values.
    I used a set of "WHEN conditions" that called the same
    static functions to get the exact same values that the user should
    pass in.
    When I try to store this new version, I get the error:
    "PLS-00587: a static method cannot be invoked on an instance value"
    It points to the first "when statifc_function()" of the case function.
    This seems weird!
    If I can call the static method from the "type object" without creating
    and instance of an object, then why can't I call it within the body
    of a method of an instance of the object type?
    This doesn't seem appropriate,
    unless this implementation of objects is trying to avoid some type
    of "recursion"?
    If there is some other reason, I can not think of it.
    Any ideas?

    Sorry for the confusion. Here is the simplest example of what
    I want to accomplish.
    The anonymous block is a testing of the object type, which definition follows.
    declare
    test audit_info;
    begin
    test := audit_info(...);
    test.testcall( audit_info.t_EMPLOYER() );
    end;
    -- * ========================================== * --
    create or replace type audit_info as object
    ( seq_key integer
    , static function t_EMPLOYER return varchar2
    , member procedure test_call(input_type varchar2)
    instantiable
    final;
    create or replace type body audit_info
    as
    ( id audit_info
    static function t_EMPLOYER return varchar2
    as
    begin
    return 'EMPLOYER';
    end;
    member procedure test_call(input_type varchar2)
    as
    begin
    CASE input_type
    WHEN t_EMPLOYER()
    select * from dual;
    WHEN ...
    end case;
    end;
    end;
    The error occurs on the "WHEN t_EMPLOYER()" line. This code is only
    an example.
    Thanks.

  • Problem with instantiation in static function

    I have a problem with instatiation of objects in a static function. When I do something like this,
    public static void test1() {
    String s = new String();
    everything works fine, but when I try to do the same with a internally defined class, I get the error "non-static variable this cannot be referenced from a static context".
    My code looks roughly like this:
    public static void test2() {
    Edge e = new Edge();
    class Edge {
    public int y_top;
    public double x_int;
    public int delta_y;
    public double delta_x;
    The compiler complains with the mentioned error message over the creation of a new Edge object and I don't have the slightest clue why... :| When I put the class Edge into an external file, it works.
    Can anyone help me out there?

    Your class Edge is a member of the instance of the current class. You don't have an implicit instance of the current class (the "this" reference) in a static context, therefore you get the error.
    You need to either declare Edge as static, move it outside your class, or create an explicit instance of the outer class which you use to create instances of Edge ("Edge e = new YourMainClass().new Edge()")

  • Mvc cant access repository classes from static functions in controller(mvc net c# Entity Frame work)

    I working on .net MVC Entity Framework (Code First).
    I am not able to get Datacontext in repository classes functions when i call these functions from a static function in controller . I am getting the Exception
    "An exception of type 'System.NullReferenceException'
    occurred in YYYYYY.Web.dll(Default
    project dll) but was not handled in user code
    Additional information: Object reference not set to an instance of an object."
    i need to call static functions since i had to call some functions asynchronously.Like Report generation
    This works perfectly fine when called from a non static function in controller.
    Thanks in advance
    Punnoose

    But when i call a function in repository class, With dependency Injection(NInject). 
    eg:-
     public Batch GetBatchDetail(string batchID)
                return this.db.Batches.Where(x => x.ID=batchID).FirstOrDefault();
    Db is Datacontext
    I am getting the Exception  "An exception of type 'System.NullReferenceException'
    occurred in YYYYYY.Web.dll(Default
    project dll) but was not handled in user code
    Please do help me
    regards
    punnoose

  • Static function in XSLT

    Hi,
    Could somebody tell me if i can embed a static function (ABAP) in an XSLT.
    Thanks in advance
    Rachana

    Hi,
    Thanks a lot and this should help me. But I'm not that well-versed in XSLT.
    Hence,
    I'm getting an xml namespace not defined error now.
    my XSLT looks like this
    <xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
      <xsl:strip-space elements="*"/>
      <xsl:output indent="no"/>
      <xsl:template match="TaskType">
        <asx:abap xmlns:asx="http://www.sap.com/abapxml" version="1.0">
          <asx:values>
            <TASKTYPEDESIGN>
              <SBTM_CR_TT_DESIGN>
                <ORIGINAL_LANG>
                                 <xsl:value-of select="../@origLang"/>
                </ORIGINAL_LANG>
                <sap:call-external class="CL_SBTM_XML_CONVERSION"              method="GET_SYLANGU">
              <sap:callvalue     param="EXTERNAL"   select="../@language"/>
              <sap:callvariable  param="INTERNAL"   name="SY_LANG"/>
              </sap:call-external>
              </SBTM_CR_TT_DESIGN>
             </TASKTYPEDESIGN>
           </asx:values>
        </asx:abap>
      </xsl:template>
    I tried to fit in that code there...but i guess this is not the way.
    please help

  • Abstract class and static function

    Please tell me that why a static function can't be made abstract?
    Thanks.
    Edited by: RohitRawat on Sep 9, 2009 7:45 AM

    RohitRawat wrote:
    Please tell me that why a static function can't be made abstract?
    Thanks.Because the method belongs to the class.

  • Static function issue?

    hi,
    i am having a static function which fetch some values from data base and put it to an arraylist and return this array list.
    some times the returned array list empty even though values are exists in db,all the varibles used in this static functions are local and
    this function is very frequently acceessing from diffrent threads
    when a static function calls then all the variables in the fuction will have diffrent copies right?
    in my example i wondered like one thread is executing this function then in beetween another thread comes and re initilise the variables so i am getting the abive specified error...
    please any one help ...

    My J2SE version (no EJB's, direct JDBC, no ConnectionPooling) might look something like this, except the connect and close methods are allready in my krc.utilz.jdbc.JDBC class.
    package david;
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.Properties;
    import java.util.logging.Logger;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.ResultSetMetaData;
    import java.sql.SQLException;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    class Sql
      private final String className;
      private final Logger log;
      private final Connection conn;
      public Sql() throws ClassNotFoundException, SQLException, IOException  {
        className = this.getClass().getName();
        log = Logger.getLogger(className);
        try {
          conn = connect(this.getClass().getResourceAsStream("database.properties"));
        } catch (SQLException e) {
          log.throwing(className, "noargs constructor", e);
          throw e;
       * Executes the given query and returns the resulting rows as a List(rows)
       * of Maps(Column name to value).
       * @param String sql - the sql-select-query to execute
       * @param String[] args - the query paramaters (if
       * @return List<Map<String,String>> rows
       * @throws java.sql.SQLException
      public List<Map<String,String>> select(String sql, String[] args) throws SQLException {
        final String methodName = "select";
        log.entering(className, methodName, new String[] {"sql="+sql, "args="+args});
        List<Map<String,String>> rows = new ArrayList<Map<String,String>>();
        PreparedStatement stmt = null;
        ResultSet rs = null;
        try {
          stmt = conn.prepareStatement(sql);
          for (int i=0; i<args.length; i++) {
            stmt.setString(i+1, args);
    rs = stmt.executeQuery();
    ResultSetMetaData md = rs.getMetaData();
    int numCols = md.getColumnCount();
    while (rs.next()) {
    Map<String,String> cols = new HashMap<String,String>(numCols);
    for (int c=1; c<=numCols; c++) {
    cols.put(md.getColumnName(c).toUpperCase(), rs.getString(c));
    rows.add(cols);
    } finally {
    close(rs, stmt, null);
    log.exiting(className, methodName, "rows="+rows.size());
    return rows;
    public void close(ResultSet rs, PreparedStatement st, Connection cn) {
    if(rs!=null)try{rs.close();}catch(SQLException e){log.severe(e.toString());}
    if(st!=null)try{st.close();}catch(SQLException e){log.severe(e.toString());}
    if(cn!=null)try{cn.close();}catch(SQLException e){log.severe(e.toString());}
    * Connects to the database specified in the given connectionProperties.
    * @param propertiesStream a java.io.InputStream from which to read
    * java.util.Properties - Example contents:
    * jdbc.driver=com.mysql.jdbc.Driver
    * jdbc.url=jdbc:mysql://localhost/test
    * jdbc.username=user
    * jdbc.password=pass
    * @return Connection - an open connection to the given database.
    * @throws ClassNotFoundException if the class named in the
    * jdbc.driver property can't be initialized.
    * The root cause exception is enclosed.
    * Double check the name of the driver class in the properties file.
    * Ensure that the named driver class exists is in the classpath.
    * @throws SQLException if a database access error occurs.
    * The root cause exception is enclosed.
    * Check the jdbc.url, jdbc.username, and jdbc.password properties.
    private Connection connect(InputStream propertiesStream)
    throws IOException, ClassNotFoundException, SQLException
    Properties props = new Properties();
    props.load(propertiesStream);
    String driver = props.getProperty("jdbc.driver");
    String url = props.getProperty("jdbc.url");
    String username = props.getProperty("jdbc.username");
    String password = props.getProperty("jdbc.password");
    try {
    Class.forName(driver).newInstance();
    } catch (ClassNotFoundException e) {
    throw e;
    } catch (Exception e) {
    String msg = "Failed to connect to url: "+url+" as "+username+" via driver "+driver;
    throw new ClassNotFoundException(msg, e);
    try {
    return DriverManager.getConnection(url, username, password);
    } catch (SQLException e) {
    String msg = "Failed to connect to url: "+url+" as "+username+" via driver "+driver;
    throw new SQLException(msg, e);
    BTW... search the forums and you'll find something similar to (but a tad more flexible than) this... I wrote a simple "squirrel" in swing about a year or so ago... execute the query, populate a table with the results.
    Another trick is the close the database connection on ANY SQLException (to keep it clean)... easy when you use a connection pool.
    Cheers. Keith.
    Edited by: corlettk on 7/11/2008 00:47 ~~ Wrong file. Doh!

  • Member /static function and procedure

    hi guys,
    i'm trying to figure out diffrerences between the following;
    1. member function and static function
    2.*member* procdure and static procedure.
    i wanna know when to use them when creating an object type.thanks.

    hope this enlighten you
    http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14261/objects.htm#CHDEFBEA

  • Using static function in c++

    Hi,
    I'm using an static function on C++ program, as :
    static int lRead(char ptr, Socket pSock);
    but when I compiled recived the following error:
    Error: "static" is not allowed here.
    any idea about how do i need to set static functions and variables?
    regards,

    You really should provide more information, but the statement looks fine. Probably, you've got a syntax error earlier in the translation unit, possibly in an include file.
    ... Dave

  • How do i create a static function in a class and implement ActionListener?

    i am trying to create a pop up dialog box in a seperate class.
    and i want to make the Function static, so that i only need to access it with the class name.
    But how do i have a ActionListener ?
    everything in a static function is static rite?

    import java.awt.*;
    import java.awt.event.*;
    public class StaticFunction
        Dialog dialog;
        private Panel getUIPanel()
            Button button = new Button("show dialog");
            button.addActionListener(new ActionListener()
                public void actionPerformed(ActionEvent e)
                    if(dialog == null)
                        dialog = OutsideUtility.showDialog("hello world");
                    else if(!dialog.isVisible())
                        dialog.setVisible(true);
                    else if(dialog.isVisible())
                        dialog.dispose();
                        dialog = null;
            Panel panel = new Panel();
            panel.add(button);
            return panel;
        private WindowListener closer = new WindowAdapter()
            public void windowClosing(WindowEvent e)
                System.exit(0);
        public static void main(String[] args)
            StaticFunction sf = new StaticFunction();
            Frame f = new Frame();
            f.addWindowListener(sf.closer);
            f.add(sf.getUIPanel());
            f.setSize(200,100);
            f.setLocation(200,200);
            f.setVisible(true);
    class OutsideUtility
        public static Dialog showDialog(String msg)
            Button button = new Button("top button");
            button.setActionCommand(msg);
            button.addActionListener(new ActionListener()
                public void actionPerformed(ActionEvent e)
                    Button button = (Button)e.getSource();
                    System.out.println(button.getActionCommand() +
                                       " from anonymous inner listener");
            button.addActionListener(new ButtonListener());
            Button anotherButton = new Button("bottom button");
            anotherButton.setActionCommand("another button");
            anotherButton.addActionListener(localListener);
            Panel north = new Panel();
            north.add(button);
            Panel south = new Panel();
            south.add(anotherButton);
            Dialog dialog = new Dialog(new Frame());
            dialog.addWindowListener(closer);
            dialog.add(north, "North");
            dialog.add(new Label(msg, Label.CENTER));
            dialog.add(south, "South");
            dialog.setSize(200,200);
            dialog.setLocation(425,200);
            dialog.setVisible(true);
            return dialog;
        private static WindowListener closer = new WindowAdapter()
            public void windowClosing(WindowEvent e)
                Dialog dialog = (Dialog)e.getSource();
                dialog.dispose();
        private static ActionListener localListener = new ActionListener()
            public void actionPerformed(ActionEvent e)
                Button button = (Button)e.getSource();
                System.out.println(button.getActionCommand() +
                                   " from localListener");
        private static class ButtonListener implements ActionListener
            public void actionPerformed(ActionEvent e)
                Button button = (Button)e.getSource();
                String ac = button.getActionCommand();
                System.out.println(ac + " from ButtonListener");
    }

  • Is Using Static functions advisable from performance(speed) point of view

    I was wondering if using a static function would be slower than using a normal function, especially when the function is to be accessed by multiple threads since the same memory area is used each time the static function is accessed from any of the threads. Thus is it right if I say that static functions are not suitable for multiThreaded access ?

    I was wondering if using a static function would be
    slower than using a normal function,Static functions are linked at compile time, while normal functions have to be linked based on the runtime type of the object they are called on. This lookup means that static function invocations are likely to be faster.
    especially when
    the function is to be accessed by multiple threads
    since the same memory area is used each time the
    static function is accessed from any of the threads.If you are talking about the code segment, where the function definition is held, there is only a single copy of each "normal" function as well. The code segment is also read-only, so there are no issues with multiple threads reading and executing the same code at the same time.
    There are the normal issues with multi-threaded access to variables in static functions that exist with normal functions.
    Thus is it right if I say that static functions are
    not suitable for multiThreaded access ?Static functions are no safer than non-static functions in terms of thread safety. On the other hand, it is no more dangerous having multiple threads calling a static function than having multiple threads calling a non-static function on the same object. Exactly the same thread safety techniques apply whether you are working in a static or a non-static context.
    With the above in mind, there is a great deal of design difference between static functions and non-static functions. They mean very different things when creating a system, and an operation that is suited for a static function is very likely not appropriate in a non-static context, and vice versa. The important thing is to make sure the design is appropriate for what the system is trying to do.
    The most common use of static functions is for object creation... The Factory design pattern uses static methods to create objects of a given type, the Singleton design pattern uses static methods to allow access to itself.

  • How to trace static functions inside binary?

    Hello Everybody
    Is it possible to trace all statically linked functions inside some application with DTrace?
    Here is an explanation. I have an application with source code like this:
    int main(int argc, char * argv[])
         custom_init();
         �
    void custom_init()
         function1();
    function2();

    This code compiled into one binary so all functions like function1, function2 and so on are �statically linked�. I�d like to see calls tree say for function custom_init. I do not know all function names that maybe called from custom_init so I need to log everything down from custom_init.
    Is this possible with DTrace if I only have a binary and it contains symbolic info?
    Thank you

    jonathan
    Thanks, I got huge list of function names with
    supplied command (# dtrace -l -n
    'pid$target:myprog::entry' -c /myprog)
    Now I'd like to trace all that comes from function
    myfunc() inside binary myprog - how do I do this?The usual idiom for this is something like:
    # cat > trace.d <<EOF
    #!/usr/sbin/dtrace -s
    #pragma D option flowindent
    pid$target:a.out:myfunc:entry
            self->on++;
    pid$target:a.out::entry
    /self->on/
    pid$target:a.out::return
    /self->on/
    pid$target:a.out:myfunc:return
    /self->on/
            self->on--;
    pid$target:a.out:myfunc:return
    /self->on <= 0/
            exit(0);        /* we've gotten the data we wanted, so exit dtrace */
    EOF
    # chmod +x trace.d
    # ./trace.d -c 'command args'
    ...This will only get the static functions in the binary; to get all shared library functions as well, s/:a.out::/:::/g.
    Inside the {}s for :entry and :return, you can do additional work; for
    example, you could print a nanosecond timestamp:
    trace(timestamp);
    or (for ::return) the return value:
    trace(arg1);
    etc.
    Cheers,
    - jonathan

  • Static function

    Hi,
    can static function be overridden? and if yes, then is it a good practice to use it or we sould avoid this?
    Thanks
    sumit

    Here is block of code in which the static method getting overridden in its subclass. But most of the person says that static method cant be overidden. Is it true or false.
    public class ParentClass {   
    public ParentClass() {
    public static void main(String args[]){
    public static void msg(){
    System.out.println("hi");
    class SubClass extends ParentClass{
    public static void msg(){
    System.out.println("hello");
    }

  • Static function parameter help

    Hi,
    I have two functions in the same file, how can I use the first function as default value in the second function.
    public static function get decimalFormatter1():NumberFormatter{
    I try this:
    public static function secondFunction(param1:String, param2:Int=0, param3:Function=decimalFormatter1):Array{
    Getting error: -1047: Parameter initializer unknown or is not a compile-time constant.
    Any ideas?
    Thanks!

    Thanks for you reply and help Gordon.
    I am getting this error at the decimalFormatter1 line:
    -1067: Implicit coercion of a value of type mx.formatters:NumberFormatter to an unrelated type Function.
    Here is my simple get function:
    public static function get decimalFormatter1():NumberFormatter{
              var decimalFormatter:NumberFormatter = new NumberFormatter();
              decimalFormatter.rounding = "nearest";
              decimalFormatter.precision=1;
              decimalFormatter.useNegativeSign = false;
              return decimalFormatter;
    Any other way?

  • Question about synchronized static function.

    Hi, everyone!
    The synchronized statement often deals with an object (called monitor).
    But a static function can be invoked without an object.
    So if a static function is declared as static, what is the function of
    static and synchronized here? Which lock it is using?
    Can you give me a simple expplanation?
    regards,
    George

    Hence try and avoid synchronizing static methods.
    Try and use non static method if you are doing
    multithreaded programming. That way you can have lockWell, I avoid static methods, not just when doing multithreading, but not for the reason you mention.
    objects which allow non interfering methods to be
    accessed in parallelThats easy to do with static methods anyway:
    class Foo
      static Object lock1 = new Object();
      static Object lock2 = new Object();
      static void method1()
         synchronized( lock1 )
      static void method2()
         synchronized( lock2 )
    }Maybe I just missunderstod you...

Maybe you are looking for

  • Satellite A300D-15B PSAKCE - USB message appears if BT is enabled

    Sorry if I'm one of those annoying people who has been posted something that's already been posted. A couple of weeks ago, my laptop a Satellite A300D-15B series (PSAKCE 00K0DEN) kept coming up with a msg - "USB DEVICE NOT RECOGNIZED" - when nothing

  • Web browser processes use over 100% CPU (OS 10.6.8)

    Hey, I know this problem has come up a lot in the last couple of years, but I've looked everywhere, at every thread and possible solution to my problem and none have ever worked, so as a last resort I'm going to just straight up ask bout again and ho

  • Where is the Equalizer in iTunes 9?

    I've been trying to figure this out for half an hour. It's probably right in front of me, but I can find it. Is there an equalizer in iTunes 9? If so, how do I get to it? Thanks in advance, Ryan

  • Do I need to update Bootcamp 3.3 after upgrading from Snow Leopard to Mountain Lion?

    Do I need to update Bootcamp 3.3 after upgrading directly from Snow Leopard to Mountain Lion? If so, what is the recommended version for my machine? Other pros and cons we should consider? Not sure what is considered best practice. We have a mid-2011

  • Error while using execute immediate

    Hi, I am trying to get the record count of a table. The table name is saved in a variable.. when i am writing the code like below its working fine. SELECT count(*) into count1 FROM emp1; DBMS_OUTPUT.PUT_LINE(count1); but when i am using the code for