Calling static synchronized method in the constructor

Is it ok to do so ?
(calling a static synchronized method from the constructor of the same class)
Please advise vis-a-vis pros and cons.
regards,
s.giri

I would take a different take here. Sure you can do it but there are some ramifications from a best practices perspective. f you think of a class as a proper object, then making a method static or not is simple. the static variables and methods belong to the class while the non-static variables and methods belong to the instance.
a method should be bound to the class (made static) if the method operates on the class's static variables (modifies the class's state). an instance object should not directly modify the state of the class.
a method should be bound to the instance (made non-static) if it operates on the instance's (non-static) variables.
you should not modify the state of the class object (the static variables) within the instance (non-static) method - rather, relegate that to the class's methods.
although it is permitted, i do not access the static methods through an instance object. i only access static methods through the class object for clarity.
and since the instance variables are not part of the class object itself, the language cannot and does not allow access to non-static variables and methods through the class object's methods.

Similar Messages

  • Multiple static synchronized methods locking the same object ?

    If I have multiple static synchronized methods in a class will all the methods lock on the same (Class) object ? I guess the answer to this would be yes. In that case is it possible achieve synchronization without an object ie code level synchronization ? If yes, how ?

    If I have multiple static synchronized methods in a
    class will all the methods lock on the same (Class)
    object ? I guess the answer to this would be yes. In
    that case is it possible achieve synchronization
    without an object ie code level synchronization ? If
    yes, how ?There is nothing special about static synchronized methods vs. any other synchronization. It's just shorthand for syncing on the Class object for that class. The effects of synchronization are identical no matter what you sync on.
    There's no way to achieve synchronization without an object. Synchronizing always obtains an object's lock. In the case of static synced methods, the object whose lock we obtain is the Class object for that class. As far as syncing goes, it's just another object.
    There is no such thing as "code level synchronization" vs. any other kind. All syncing occurs in your Java code over blocks of code. For synced methods, those blocks are the entire respective method bodies.
    Having said all that, I have no idea what you're really after or what you're trying to achieve.

  • Intrinsic locks - static synchronized method

    I am trying to understand the "static synchronized threads" - by theory when such a thread is invoked, it has to obtain a intrinsic lock on all the static variables. I wrote a sample program, but it is not giving me the desired results.
    I have 3 threads, t1, t2, t3. t1 calls a static synchronized method crazy(), where i am using static int i. t2 and t3 calls a void function f2() and f3() which just prints i. Now i put a sleep in synchronized method crazy. I am expecting t1 to start and print i and go to sleep for 10 secs, release i and then t2 and t3 starts since crazy() holds an intrinsic lock on i. But the program calls t2 and t3 even if crazy puts the thread to sleep. What happend to the intrinsic lock on i ??
    class RunnableThread implements Runnable{
    static String i;
    void f2() {
    RunnableThread.i = "Two";
    System.out.println(RunnableThread.i);
    void f3() {
    this.i = "three";
    System.out.println(this.i);
    static synchronized void crazy() {
    try {
    i = "One";
    System.out.println(i);
    Thread.sleep(10000);
    System.out.println("Sleep done");
    catch (Exception e ) {
    e.printStackTrace();
    public void run() {
    System.out.println("Thread Name: " + Thread.currentThread().getName());
    if (Thread.currentThread().getName().equals("two"))
    f2();
    } else if (Thread.currentThread().getName().equals("three"))
    f3();
    else if (Thread.currentThread().getName().equals("one"))
    RunnableThread.crazy();
    public static void main(String args[]) {
    System.out.println("SOP from main");
    RunnableThread rt1 = new RunnableThread();
    RunnableThread rt2 = new RunnableThread();
    RunnableThread rt3 = new RunnableThread();
    Thread t1 = new Thread(rt1, "one");
    t1.start();
    Thread t2 = new Thread(rt2, "two");
    t2.start();
    Thread t3 = new Thread(rt3, "three");
    t3.start();

    lavanya.km wrote:
    I am trying to understand the "static synchronized threads"Never heard of it. You might want to clarify your terminology.
    - by theory when such a thread is invoked, it has to obtain a intrinsic lock on all the static variables. Nope. Doesn't happen.
    I wrote a sample program,Ah, I see. You're creating synchronized static methods. Those do not even come close to "obtaining an intrinsic lock on all the static variables," even if there were such a thing as an "intrinsic lock," which there isn't. A synchronized method is just shorthand for enclosing the entire body in a sync block. In the case of a non-static method, it syncs on the "this" object. In the case of a static method, it syncs on the Class object for the class where the method is declared.
    In no case does anything sync on "all the variables," static or not.

  • Static synchronized methods VS non-static synchronized methods ??

    what is the difference between static synchronized methods and non-static synchronized methods as far as the behavior of the threads is concerned? if a thread is in static synchronized method can another thread access simple (ie. non static) synchronized methods?

    javanewbie80 wrote:
    Great. Thanks. This whole explanation made a lot of sense to me.Cool, glad I was able to help!
    Probably I was just trying to complicate things unnecessarily.It's a classic case of complexity inversion. It seems simpler to say something like "synchronization locks the class" or "...locks the method" than to give my explanation and then extrapolate the implications. Just like the seemingly simpler, but incorrect, "Java passes objects by reference," vs. the correct "Java passes references by value," or Java's seemingly complex I/O vs. other languages' int x = readInt(); or whatever.
    In the seemingly complex case, the primitive construct is simpler, but the higher level construct requires more assembly or derivation of the primitive constructs, making that case seem more complicated.
    Okay, I just re-read that, and it seems like I'm making no sense, but I'll leave it, just in case somebody can get some meaning out of it. :-)

  • Static synchronized method

    hi,
    I am unable to understand the concept of static synchronized method.
    A non-static synchronized method gets lock on this object before entering into the method. But how this is valid for static method.
    thanks in advance

    hi,
    I am unable to understand the concept of static
    atic synchronized method.
    A non-static synchronized method gets lock on
    this object before entering into the method.
    But how this is valid for static method.
    thanks in advanceIt locks the YourClassName.class object.

  • How to call a bean method in the faces-config file?

    Hi,
    I would like in my menu to call the method of a bean (it initialize some properties before opening the page) instead of opening directly the page, by I can't find how to do that.
    I tried :
    <managed-property>
    <property-name>viewId</property-name>
    <value>#{listInformationsController.listInformations}</value>
    </managed-property>
    And :
    <managed-property>
    <property-name>outcome</property-name>
    <value>#{listInformationsController.listInformations}</value>
    </managed-property>
    With no success...
    Can someone help me?
    Thank you and merry christmas !

    Hi,
    a managed property only gives you a anlde to a bean or property, it doesn't execute it. To execute a bean, you can use a custom JSF PhaseListener that calls a bean method. The reference to the bean is achieve through value binding
    ValueBinding vb = FacesContect.getCurrentInstance().getApplication().createValueBinding("Name of Managed Bean);
    TypeOfBean theBean =(TypeOfBean) vb.getValue(FacesContext.getCurrentInstance());
    .... theBean.theMethod() ...
    Frank

  • Static factory methods, instead of constructor

    Hi All,
    why we use static factory methods, instead of constructor.
    Apart from Singleton class , what is use of static factory methods ?
    Thanks in Advance,
    Rishi

    One reason for using factories is that they simplify creating instances of immutable classes that might otherwise have messy constructors with lots of arguments.

  • Use of an overriden method in the constructor

    Hi.
    I have a base class A whith the methode f() and
    a class B which inherits from A and overrides de
    method f().
    I use f() in the constructor of A.
    My question is: in the A constructor, how to avoid the usage of the overriden method. I need
    to call A.f() not B.f().
    Following is a piece of code desmonstrating the problem:
    class A {
    String s;
    public A(String s) {
    System.out.println(">>>> Begin constructor A ... ");
    f(s); // How to call call A:f() instead of the overriden B.f()
    System.out.println(">>>> End constructor A .");
    void f(String s) {
    System.out.println("Entering A:f() ... ");
    this.s = s;
    public class B extends A {
    public B(String s) { super(s); }
    void f(String s) {
    System.out.println("Entering B:f() ... ");
    super.f(s);
    public static void main(String[] args) {
    B b = new B("Hello world !\n");
    b.f("Bonjour le monde !\n");
    The result I want is :
    Begin constructor A ...Entering A:f() ...
    End constructor A .Entering B:f() ...
    Entering A:f() ...
    but I can only have:
    Begin constructor A ...Entering B:f() ...
    Entering A:f() ...
    End constructor A .Entering B:f() ...
    Entering A:f() ...
    Thanks in advance, Christophe.

    You cannot do that. A good work around is to implement a private version of the method, then call the private version in the public method.
    Here is how I would implement this with your classes (I changed f() to foo())
    class A {
        String s;
        public A(String s) {
            System.out.println(">>>> Begin constructor A ... ");
            fooImpl(s); // Call the private implementation method
            System.out.println(">>>> End constructor A .");
        void foo(String s) {
            fooImpl(s);
        private void fooImpl(String s) {
            System.out.println("Entering A:f() ... ");
            this.s = s;
    public class B extends A {
        public B(String s) { super(s); }
        void foo(String s) {
            System.out.println("Entering B:f() ... ");
            super.foo(s);
        public static void main(String[] args) {
            B b = new B("Hello world !\n");
            b.foo("Bonjour le monde !\n");
    }

  • Setters method in the constructor

    Hi everyone;
    I am having some trouble with one of my constructor. I am trying to write my constructor as strong as possible to avoid some wrong input by the user during the running time.
    Therefore I decided to write setter methods and then use them in my constructor, but when I tried to test my class with JUnit, the test failed and I don't know why !
    This is my code :
    //CONSTRUCTOR:
          * Creates a new item with a given quantity and price.
          * The constructor use three helper methods.
          * @param itemName
          *                          enter a String for the name of the item.
          * @param itemQuantity
          *                               enter an integer for the quantity of the item.
          * @param itemPrice
          *                               enter a double for the price of the item.
         public Item(String itemName, int itemQuantity, double itemPrice) {
              setItemName(itemName);
              setItemQuantity(itemQuantity);
              setItemPrice(itemPrice);
    //SETTER METHODS:
          * Set the quantity of item available in stock.
          * @param itemQuantity
          *                               enter an integer for the quantity of item.
         public void setItemQuantity(int itemQuantity) {
              if (itemQuantity > 0) {
                   this.itemQuantity = itemQuantity;
              } else {
                   throw new IllegalArgumentException("The amount must"
                             + " be greater than zero.");
          * Set the price of the item.
          * @param itemPrice
          *                          enter a double for the price of the item.
         public void setItemPrice(double itemPrice) {
              if (itemPrice > 0) {
                   this.itemPrice = itemPrice;
              } else {
                   throw new IllegalArgumentException("The price must be "
                             + "greater than zero");
    //JUNIT TEST:
          * Create a new object item.
         private Item item;
          * Set up the test by initialising the new item.
          * @throws Exception (expected = IllegalArgumentExeption.class)
         @Before
         public void setUp() throws Exception {
              item = new Item("Bible", 10, 20.0);
         @Test
         public void constructor() {
              item.getItemName();
              assertEquals("Bible", item.getItemName());
              assertEquals(10, item.getItemPrice());
         }I tested my two setter methods and they work properly in normal and boudary cases.
    In my Junit test, when I try to get the item price i have the error : expected IllegalArgumentException.
    Does someone have an idea ?
    Thank you,
    Henri

    by the way if your constructor is going to call another method (like the setters) then either the class or the called methods should be final. Otherwise subclasses could change the behavior of the constructor, which is a bad place for behavior to go out of hand.
    And generally you're better off designing inheritance into the the design, such that overrideable methods are clearly defined as such and everything else is private or final.
    Just my experience, YMMV, etc.

  • How to call  a javascript method after the PPR event has finished  ?

    Hi!
    How can we make a javascript method get called after the processing of ADF PPR event?
    My specific use case is,
    I want to call a javascript function after the data in the table is loaded...
    In 10g, that is not a problem, as the data used to get loaded directly during onLoad, and so i would call my js function on load;
    but in 11g , the table data is being loaded through PPR which is initiated onload, and so i needed to call my function after the PPR Response processing has been done; for which I need the name of the event triggered at that instance.
    Is it possible to do this?
    Regards,
    Samba

    Hey, I got it.
    I handled the ADF Controller's PREPARE_RENDER_ID phase of the lifecycle, and then called the
    script to get Executed.
    The code :
        public void afterPhase(PagePhaseEvent pagePhaseEvent) {
            FacesPageLifecycleContext ctx = (FacesPageLifecycleContext)pagePhaseEvent.getLifecycleContext();
                 if (pagePhaseEvent.getPhaseId() == Lifecycle.PREPARE_RENDER_ID) {
                    if(AdfFacesContext.getCurrentInstance().isPostback() )
                        afterRender();
        }is written in lifecycle listener , and my backing bean extended this listener ,
    and in the afterRender() method I did this :
       public void  afterRender(){
                System.out.println("AFTER RENDER CALLED");
               FacesContext context = FacesContext.getCurrentInstance();
               ExtendedRenderKitService service = (ExtendedRenderKitService)Service.getRenderKitService(context, ExtendedRenderKitService.class);
               service.addScript(context, "translate();");
           }That's it.
    It did work, magnificently.
    Thanks for the idea.
    Regards,
    Samba

  • How to call standard SAP method in the Custom Program ?

    Hi,
    i need to call sap standard method 'OpenItemRollinout' in my custom program. For the SAP Standard method 'OpenItemRollinoun' the BOR(Business Object) is 'PAYSCHEME'. So how to call the SAP standard method in the custom program ???

    Hi,
    In the method that you have provided only one function module is being used so better use the FM and copy the remaining code based on ur requirement.
    FM is ISU_S_PAYSCHEME_ROLLIN_ROLLOUT.
    Regards,
    Vijay.

  • Calling Stateful & Statless Methods from the same Entity Bean[EJB2.0]?

    Dear All,
    We using EJB2.0........
    Regarding segregation of stateless and stateful methods..These methods are defined in Session bean.Now my question is
    Is it a good practice to call Stateful and Stateless business methods from same single entity bean("EntityBean") defined at program level by extending MainBean..
    The architecture is like
    public class EntityBean extends MainBean
    Public Methodxyz
    stfobj.MakeConn();
    stlobj.getXyz();
    stfobj.CloseConn();
    Public Class MainBean{lookup("stl");lookup(stf) ;stl_obj=home.create;stf_obj=home.create()............}
    ejb-jar.xml
    { <session>
              <description>Entity Bean Employee Example</description>
              <ejb-name>stl</ejb-name>
              <local-home>com.packg.stlHome</local-home>
              <local>com.packg.stl</local>
              <ejb-class>com.packg.stlBean</ejb-class>
              <session-type>Stateless</session-type>
              <transaction-type>Container</transaction-type>
         </session>
         <session>
              <description>Entity Bean Employee Example for stateful</description>
              <ejb-name>stf</ejb-name>
              <local-home>com.packg.stfHome</local-home>
              <local>com.packg.ejbeans.stf</local>
              <ejb-class>com.packg.stfBean</ejb-class>
              <session-type>Stateful</session-type>
              <transaction-type>Container</transaction-type>
         </session>
         <session>
              <description>Session bean for System Parameters</description>
              <ejb-name>SysParam</ejb-name>
              <local-home>com.packg.Home</local-home>
              <local>com.packg.Param</local>
              <ejb-class>com.packg.Bean</ejb-class>
              <session-type>Stateless</session-type>
              <transaction-type>Bean</transaction-type>
              <ejb-local-ref>
              <ejb-ref-name>stl</ejb-ref-name>
              <ejb-ref-type>Session</ejb-ref-type>
              <local-home>com.packg.stlHome</local-home>
              <local>com.packg.ejbeans.stl</local>
              <ejb-link>stl</ejb-link>
         </ejb-local-ref>
              <ejb-local-ref>
              <ejb-ref-name>stf</ejb-ref-name>
              <ejb-ref-type>Session</ejb-ref-type>
              <local-home>com.packg.stfHome</local-home>
              <local>com.packg.stf</local>
              <ejb-link>stf</ejb-link>
         </ejb-local-ref>
         </session>
    Thanks !!
    Edited by: user9052593 on Jun 18, 2012 2:20 AM
    Edited by: user9052593 on Jun 18, 2012 2:25 AM

    All Business logic resides in session beans[Stateful or Stateless]..For stateful beans we are opening connections in entity bean ,calling business methods and closing connection in entity bean itself..Problem is
    I am doing lookup for stateful and stateless both since both objects are called by extending MainBean in same entity bean else will give null pointer exception..
    So whenever i call a Stateful or Stateless method from entity bean Which ultimately extends/calling MainBean and thereby calling home.create methods of stateful and stateless both..creating objects..Is this way fine or it will affect the performance?
    Do i need to segregate the Calls/invokation to Stateful / Stateless methods at entity bean level too..
    For ex:- Whenever i call Methodxyz() method ..at the same time it create 2 objects as its extending MainBean...i want to extend/create 1 object either of stateful or stateless one for stateful and stateless methods call respectively..
    See the code in entity bean is like
    public class EntityBean extends MainBean
    Public Methodxyz
    stfobj.MakeConn(); call to stateful method defined in stateful bean
    stlobj.getXyz();// call to stateless method defined in stateless bean
    stfobj.CloseConn(); call to stateful method defined in stateful bean
    ------------------------------------------------------------

  • Static synchronized methods

    Hi
    Why dont we declare static methods synchronized especially if they are doing some complex calculation on some passed arguments ?
    thanks
    ali

    lucky_ali80 wrote:
    Hi guys
    Thanks for your quick replies. But i am still a bit confused.Then you're making it more complicated than it is.
    You synchronize a block of code when you want to makes sure only one thread at a time can obtain a given lock for that block of code. You declare an instance (non-static) method synchronized as a shorthand for synchronizing the block that is its body on this, and you declare a class (static) method synchronized as a shorthand for synchronizing its body on the Class object for that class.
    >
    For e.g my static function looks some thing like the one below:
    public class MyClass
    public static int computeSomething ( int a , int b)
    // a number of lines of complex computation on a and b
    return result.
    Now Say its a webserver running with object1, object2, 3...10 of the same type being maintained by the server. (Not threads but objects)
    say all these objects simultaneously call my static function with their respective arguments.
    Would this cause any synchronization issues??No. As I said in my first reply, every thread has its own copy of local variables. This includes method parameters. Each thread has its own a and b here.
    Now, if you're using some other data besides a and b, and if that data is shared among multiple threads, then you may have an issue. We can't say for sure because there are many different possible scenarios.
    Edited by: jverd on Feb 10, 2009 11:58 AM

  • Is there a tutorial on - how to call static java methods

    I have defined external JAVA resource using a .jar file and have successfully catalogged the same. Now I need to pass variables to a static method in a class and also get the return variable mapped into a BPM variable.
    Can someone share sample Java Invokation code, how to call methods in a class, how to instantiate a singleton or reference an existing instance of singleton class.
    Any sample code or sample projects will be useful.
    Also can I se ethe java system.out.println output in BPM Logviewer
    Arvind

    Hi Arvind,
    Sure you've done this, but the first step is to catalog the Jar file. Before an Oracle BPM project can use the Java component, the appropriate Java JAR files must be added to the project.
    Add the Jar File(s) to the External Resources:
    1. Right-click the External Resources item in the Project Navigator tab
    2. From the pop-up menu, select New External Resource.
    3. Name this new Java resource "MyNewJavaComponents" and ensure its type is Java Class Library.
    4. Add the Java jar file(s)
    Catalog and Expose the Java Components:
    5. Add a new module in the Catalog called "IntegrationComponents".
    6. Generate a Java integration component by right-clicking the IntegrationComponents module and select "Catalogue Component" -> "Java".
    7. Using the Java configuration you just created called MyNewJavaComponents, click the Next button to automatically introspect the Java libraries.
    8. Select the class where your method(s) are located and click the Next -> Finish buttons to have Oracle BPM generate the integration component for you.
    9. If you expand the newly exposed Java component, you can see a method has been created for each public method (attributes would also be automatically created if this class had any public attributes). If you've included the appropriate BeanInfo class in the JAR, you'll note that the method parameters are appropriately named.
    How to Invoke Public Java methods Exposed in the Catalog:
    10. Open the method editor for an automatic activity in the process (or any BPM Object method with its "Server Side" property set to "Yes").
    11. Drag one of the Java methods you just exposed inside your IntegrationComponents module into the automatic activity's method. Once you drag it in, here's what you might see if you're using the Java syntax in Oracle BPM's method editor:
    (PdfGenerator).generate(outputFilename : "", contents : {  }, logoImageURL : null, signatureImageURL : null);
    Assuming you have "outputFilename", "sampleContent", "logoURL" and "signatureURL" variables already created in your process, change the method you just dragged in to:
    IntegrationComponents.Pdfservice.PdfGenerator.generate(outputFilename : outputFilename, contents : sampleContent,
    logoImageURL : logoURL, signatureImageURL : signatureURL);
    Hope this helps,
    Dan

  • Calling public class method  from the servlet dopost() implementation

    Hi!
    My application is a simple application where i wrote a JSP page to enter the USERNAME and PASSWORD. And this JSP will call a HttpServlet
    with in which i am calling another Java class ValidateUser which will check aginst the Oracle Database table whether that Username and password combination exists and returns the user's name.
    But when i am trying to call that method is throwing me an error. here is the typical code i wrote.
    servlet
    package isispack;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.util.*;
    import java.io.*;
    public class Login extends HttpServlet{
    public void doPost(HttpServletRequest req, HttpServletResponse res)
                   throws ServletException,IOException{
    String userId = req.getParameter("user_id");
    String password = req.getParameter("user_pass");
    // if uName is null .. user is not authorized.
    String uName = Validate(userId, password);
    and
    Validate class
    package isispack;
    import java.sql.*;
    import java.util.*;
    import java.lang.*;
    public class ValidateUser
    public String ValidateUser(String inputUserid, String inputPwd) throws
    SQLException{
         String returnString = null;
         String dbUserid = "isis"; // our Database user id
         String dbPassword = "isisos" ; // our Database password
         Connection con = DriverManager.getConnection("jdbc:odbc:JdbcOdbcDriver","isis","osiris");
         Statement stmt = con.createStatement();
         String sql= "select user_id from isis_table where user_id = '" inputUserid + "' and user_pass= '" + inputPwd +"' ;" ;
         ResultSet rs = stmt.executeQuery(sql);
         if (rs.next())
         returnString = rs.getString("user_id");
         stmt.close();
         con.close();
         return returnString ;
    The ERROR
    Error(18,18): method ValidateUser(java.lang.String, java.lang.String) not found in class isispack.Login
    One more thing i forgot to tell you. I am trying to run this application on JDeveloper. Please helpme out if you can . Thank you.
    -Sreekanth

    OK! I made it static method
    and tried to call the method as follows
    String uName = ValidateUser.ValidateUser(userId, password);
    even if i create the instence and
    ValidateUser Validate;
    then call
    String uName= Validate.ValidateUser(userId,password)
    In either case is giving me the following error.Tarun, am new to Java programming, please help me out. And can you please tell me where can i find things in consise to brush up my fundamentals?.
    Error(18,43): unreported exception: java.sql.SQLException; must be caught or declared to be thrown

Maybe you are looking for