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

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

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

Similar Messages

  • Use VB Set keyword with Clone method?

    I am using the TestStand API with Visual Basic 6.0 SP5. Is is necessary to use the Set keyword when calling the Clone method of a PropertyObject? i.e. which is correct:
    Set thePropObj = existingPropObj.Clone("", 0)
    or
    thePropObj = existingPropObj.Clone("", 0)
    Seems the Set keyword would be required, but I am
    running into funny problems with this. I have a step
    that I am trying to create a copy of. (The step contains a call to a LabVIEW VI.) If I omit the Set keyword, execution hangs at the call to Clone. If I include the Set keyword, all information present in the original PropertyObject doesn't seem to get copied to the new one. (Also, oddly enough, if I omit the set keyword, and the step calls a CVI function, everything seems to work
    fine!)
    Anyone have any advice?
    Thanks in advance
    D. LaFosse

    Hello LaFosse,
    You need to use the Set keyword before the clone method statement. However, I have a couple of comments about the code you sent.
    This is the code you sent:
    ' Start up the testStand engine
    Dim theTS As TS.Engine
    Set theTS = New TS.Engine
    ' OK, load in the sequence file I
    ' created. This sequence file
    ' contains nothing more than a call
    ' to a VI in the main stepgroup of
    ' the MainSequence.
    Dim seqFile As SequenceFile
    Set seqFile =
    theTS.GetSequenceFile()
    ' get a handle to the MainSequence
    Dim seq As Sequence
    Set seq = seqFile.GetSequenceByName
    ("MainSequence")
    ' Get a handle to the step that calls
    ' the VI, and a property object for
    ' the step
    Dim theStep As Step
    Set theStep =
    seq.GetStep(0, StepGroup_Main)
    Dim theStepProp As PropertyObject
    Set theStepProp =
    theStep.AsPropertyObject
    ' Create another step. We will attempt
    ' to use Clone to fill in the
    ' properties of this step.
    Dim theOtherStep As Step
    Dim theOtherStepProp As PropertyObject
    Set theOtherStep = theTS.NewStep("",
    TS.StepType_Action)
    Set theOtherStepProp =
    theOtherStep.AsPropertyObject
    ' Call clone...this step will hang.
    theOtherStepProp =
    theStepProp.Clone("", 0)
    Basically the problem is that you are not loading the TypePallete after creating the engine. You shoud include right after the Set theTS = New TS.Engine:
    theTS.LoadTypePaletteFiles
    This should avoid the crash.
    Some Additional comments:
    1. With VB you don't need to create property objects from other objects. All the classes, except the Engine Class, inherit from the Property Object Class. The following Code does the same thing, but without creating propertyobjects directly:
    Sub MySub()
    'Variable Declaration
    Dim theTS As TS.Engine
    Dim seqFile As SequenceFile
    Dim seq As Sequence
    Dim theStep As Step
    Dim theOtherStep As Step
    'Create the Engine
    Set theTS = New TS.Engine
    'Load the Types
    theTS.LoadTypePaletteFiles
    'Get Sequence File
    Set seqFile = theTS.GetSequenceFile()
    'Get Sequence
    Set seq = seqFile.GetSequenceByName("MainSequence")
    'Get Step
    Set theStep = seq.GetStep(0, StepGroup_Main)
    'Clone the Step
    Set theOtherStep = theStep.Clone("", 0)
    'Using the inheritance functionality
    'gets the Step Status
    'Notice that theOtherStep is not a PropertyObject
    'and you can use all the properties and methods that
    'applies to the PropertyObject Class to a Step class
    'in this example
    'Also, in VB when you are typing the statement, you
    'will not see the PropertyObject Class properties and
    'and Methods automatically if the variable is not a
    'PropertyObject type. However, you can still use them
    'as mentioned before
    MsgBox (theOtherStep.GetValString("Result.Status", 0))
    End Sub
    2. When you create or modify sequence files programatically be carefull not to break the license Agreement. You need the development lisence when modifying sequences.
    3. This piece of code is not completed, and you will need to shutdown the engine by the end.
    4. Since you are not handling UI Messages, you will need to be carefull when loading sequences that have the SequenceFileLoad Callback. The engine posts UI Messages when executing this callback. Also when you shutdown the engine, UI Messages are posted. For both operations (Load Sequence and Shuutdown) you may prevent the engine from posting the message (You may check the options parameter for this two methods in TS Programmer Help.)
    5. If you want to run a sequence, again you will need to incorporate in your code the UIMessage Handler part. (You may check the TS Programmer Help->Writing an Application Using the API->UI Messages). Otherwise it may hang since the engine posts UI Messages eventually.
    Regards,
    Roberto Piacentini
    National Instruments
    Applications Engineer
    www.ni.com/support

  • Use of static keyword appropriate in this context?

    Hello all,
    I have an application that has a class that I would like all other classes to be able to access. What i'm unsure of is how to implement this correctly or should this even be done. For example consider the following:
    Main Class
    public class Main {
        public static void main(String[] args) {
            new Main();
        static SecondClass secondClass = new SecondClass();
        public Main() {
    Second Class
    public class SecondClass {
        public void method() {
            System.out.println("Method in Second Class");
    Third Class
    public class ThirdClass {
        public void doSomething() {
            //is this appropriate?
            Main.secondClass.method();
    }Now I know I could just pass an instance of the Second Class to all classes that need to use the Second Class but I thought it might be easier just to declare the instance of the Second Class static so that I could do the following to access it easily considering I will only ever need one instance of the class:
    Main.secondClass.method();
    So my question is would this approach be appropriate or is it frowned upon to access a class in this way?
    Thank You. :)

    Thank you for your reply, your being real helpful, sorry i'm asking so many questions but I don't think the above code would help me in my situation. To clarify the problem i'm having I have created a small application that demonstrates it. The program is kind of a fake image viewer. The Main Class displays albums and images inside a frame. The Photos Class has one purpose and that is to load and display the images based on what "album" the user has selected. Now the Albums Class is where the problem occurs. The classes purpose is to display a list of albums for the user to choose from. When an album is clicked it needs to reload the images displayed in the Photos Class. Now the problem is i'm not quite sure how to access the Photos class from the Albums class. Right now I do the following <tt>Main.photos.loadAlbum();</tt> but i'm not sure that that is an appropriate way to access the Photos class. I need to somehow update the images that the Photos Class displays when the user selects an album in the Albums Class. I don't know if this makes any sense but I would like to keep all the classes separate for simplicities sake. I know my problem would be solved if all these classes were in one class but that one class would get pretty big and would eventually be a nightmare for debugging. But with all these classes being separate i'm just not sure how to have them communicate correctly. Thank you for your help and patients while helping me figure this out. Its much appreciated.
    Main Class
    import java.awt.*;
    import javax.swing.*;
    public class Main {
        public static void main(String[] args) {
            new Main();
        Albums albums = new Albums();
        static Photos photos = new Photos();
        static JFrame frame = new JFrame("");
        public Main() {
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(540,310);
            frame.setResizable(false);
            frame.setLocationRelativeTo(null);
            frame.setLayout(new FlowLayout(FlowLayout.CENTER));
            frame.add(new JLabel("                                     Albums (Click an image to load)                                         "));
            frame.add(albums);
            frame.add(new JLabel("                                               Images                                          "));
            frame.add(photos);
            frame.setVisible(true);
    Photos Class
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.*;
    import javax.imageio.*;
    import java.net.*;
    public class Photos extends JPanel {
        Image image, image2;
        public Photos() {
            try {
                image = ImageIO.read(new URL("http://i.ehow.com/images/a04/hb/11/meaning-lotus-flowers-200X200.jpg"));
                image2 = ImageIO.read(new URL("http://www.flowerpicturegallery.com/d/613-2/teddy+bear+sunflower.jpg"));
            catch(Exception err) {
            setOpaque(false);
            for(int i = 0; i<5; i++) {
                add(new Thumbnail(image));
        //load an "album"
        public void loadAlbum(Image image) {
            this.removeAll();
            for(int i = 0; i<5; i++) {
                add(new Thumbnail(image));
            Main.frame.validate();
        public class Thumbnail extends JLabel {
            Image displayImage = image;
            public Thumbnail(Image image) {
                displayImage = image;
                setPreferredSize(new Dimension(100,100));
                addMouseListener(new MouseListener());
                setOpaque(false);
            public class MouseListener extends MouseAdapter {
                public void mouseClicked(MouseEvent e) {
            public void paintComponent(Graphics g) {
                g.drawImage(displayImage, 0, 0, getWidth(), getHeight(), this);
    Albums Class
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.*;
    import javax.imageio.*;
    import java.net.*;
    public class Albums extends JPanel{
        Image image, image2;
        public Albums() {
            try {
                image = ImageIO.read(new URL("http://i.ehow.com/images/a04/hb/11/meaning-lotus-flowers-200X200.jpg"));
                image2 = ImageIO.read(new URL("http://www.flowerpicturegallery.com/d/613-2/teddy+bear+sunflower.jpg"));
            catch(Exception err) {
            setOpaque(false);
            add(new Thumbnail(image));
            add(new Thumbnail(image2));
        public class Thumbnail extends JLabel {
            Image displayImage = image;
            boolean clicked = false;
            public Thumbnail(Image image) {
                displayImage = image;
                setPreferredSize(new Dimension(100,100));
                addMouseListener(new MouseListener());
                setOpaque(false);
            public class MouseListener extends MouseAdapter {
                public void mouseClicked(MouseEvent e) {
                    //Here is the problem.
                    Main.photos.loadAlbum(displayImage);
            public void paintComponent(Graphics g) {
                g.drawImage(displayImage, 0, 0, getWidth(), getHeight(), this);
    }Edited by: neptune692 on Oct 9, 2010 11:19 AM

  • Should I use a static method or an instance method?

    Just a simple function to look at a HashMap and tell how many non-null entries.
    This will be common code that will run on a multi-threaded weblogic app server and potentially serve many apps running at once.
    Does this have to be an instance method? Or is it perfectly fine to use a static method?
    public static int countNonNullEntries(HashMap hm){
    if(hm==null)return 0;
    int count=0;
    for(int i=0; i<hm.size(); i++) {
    if(hm.get(i)!=null)
    { count++;}
    return count;
    OR
    public int countNonNullEntries(HashMap hm){
    if(hm==null)return 0;
    int count=0;
    for(int i=0; i<hm.size(); i++) {
    if(hm.get(i)!=null)
    { count++;}
    return count;
    }

    TPD Opitz-Consulting com wrote:
    The question is the other way around: Is there a good reason to make the method static?
    Ususally the answer is: no.The question is: does this method need state? Yes -> method of a class with that state. No -> static.
    The good thing of having this method statig is that it meight decrese memory foot pring but unless you're facing memory related problem you should not think about that.I doubt there is any difference between the memory foot print of a static or not method.
    I'm not shure if this method beeing static maks problems in multithreaded environments like the one you're aiming at. But I do know that an immutable object is always thread save.Does the method use shared state (data)? No -> no multi threaded problems.
    Can the parameters be modified by different threads? Yes, if multiple threads modified the parameter map, but nothing you can do about it here (no way to force the calling thread to lock on whatever you lock on).
    So my answer to your question is: yes, it should be non static.The method should be static since it uses no state.
    It is thread-safe when only the calling thread can modify the passed map (using a synchronized or ConcurrentHashMap is not enough, since you don't call a single atomic method on the map).
    // Better use Map instead of HashMap
    // We don't care about the generic type, but that does not mean we should use a raw type
    public static int countNonNullEntries(Map<?, ?> map) {
      // whether to accept null map or not, no need for explicit exception
      // since next statement throw NPE anyway
      Collection<?> values = map.values();
      // note your method is called countNonNull, not countNull!
      // (original code it would need to by if(null != mapValue) notNullsCounter++;
      return values.size() - java.util.Collections.frequency(values, null);
    }

  • Synchronized method in a java class used by many interfaces

    My interface (idoc to file) is using a java class, which has one method that reads a table from a central database and after doing some calculations updates it.
    (The interface instantiate the class inside a user-defined function and calls the method there.)
    The problem is that if somebody sends 100 idocs at the same time, there can be a “dirty read”, I mean, a read just before other interface updates the table.
    We want the following:
    Interface 1:
    -          Read counter from the table (counter = 5 )
    -          Increment counter (counter = 6)
    -          Update table with that counter (table with counter = 6)
    Interface 2:
    -          Read counter from the table (counter = 6 )
    -          Increment counter (counter = 7)
    -          Update table with that counter (table with counter = 7)
    RESULT: The table has the counter = 7
    But what is happening is the following:
    -          Interface 1 reads (counter = 5)
    -          Interface 2 reads (counter = 5)
    -          Interface 1 increments counter (counter = 6)
    -          Interface 2 increments counter (counter = 6)
    -          Interface 1 updates table (table with counter = 6)
    -          Interface 2 updates table (table with counter = 6)
    RESULT: The table has the counter = 6 (WRONG)
    I made the method synchronized. What I was expecting was that only one interface (i1) could enter the method (read the table and update it) while other interfaces running at the same time would have to wait until i1 finished that method.
    My first test indicates that's not happening. Can anybody help me to find a solution?

    Hi Bhavesh,
    If the QOS is EOIO this means that the integration engine manage the call to the mapping program (and all the other blocks) inside an "internal" synchronized method.
    So this means that in this case you do not need to manage the queued access (synchronization) inside your custom java code because it is already enveloped in a queued block by XI.
    The problem that Jorge had can be easily reproduced using the sample code that follows:
    <b>class Synch Object</b>
    import java.util.Date;
    public class SynchObject {
         String strName;
         public SynchObject(String strName){
              this.strName = strName;
         public synchronized void syncWrite(String strCaller) throws InterruptedException{
              Date now;
              now = new Date();
              System.out.println("-- " + now.toLocaleString() + " " + strCaller + " entering syncWrite of " + strName);
              System.out.flush();
              Thread.sleep(1000);
              now = new Date();
              System.out.println("-- " + now.toLocaleString() + " syncWrite of " + strName + " called by " + strCaller );
              System.out.flush();
              Thread.sleep(1000);
              now = new Date();
              System.out.println("-- " + now.toLocaleString() + " " + strCaller + " leaving syncWrite of " + strName);
              System.out.println("");
              System.out.flush();
    <b>class Caller</b>
    public class Caller implements Runnable {
         String strName;
         SynchObject target;
         int intMax;
         public Caller(String strName, SynchObject target, int intMax) {
              this.strName = strName;
              this.target = target;
              this.intMax = intMax;
         public void run() {
              for(int i=0; i<intMax;i++)
                   try {
                        target.syncWrite(strName);
                   } catch (InterruptedException e) {
                        e.printStackTrace();
    <b>class Workbench</b>
    public class Workbench {
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              SynchObject sObj1 = new SynchObject("syncObj1");
              SynchObject sObj2 = new SynchObject("syncObj2");
              Caller c1 = new Caller("caller1",sObj1,2);
              Caller c2 = new Caller("caller2",sObj1,2); '[*CHANGE*]
              Thread ct1 = new Thread(c1);
              Thread ct2 = new Thread(c2);
              ct1.start();
              ct2.start();
    Run the workbench class to see what happen when setting QOS EOIO (the synch object is the same).
    To see instead what happen now (missing synchronization) you have to change in Workbench class the statement
    Caller c2 = new Caller("caller2",sObj1,2); '[*CHANGE*]
    with
    Caller c2 = new Caller("caller2",sObj2,2); '[*CHANGE*]
    The reason is that every instance of the mapping program declare a new instance of the "Synchronized object" so the calls are synchronized inside the same mapping program but not between several mapping program.
    Hope this give you a better idea on this problems with java synchronization, but if you have further doubts (I know it's a little bit tricky ) feel free to ask.
    Kind Regards,
    Sergio

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

  • Which object's monitor does a synchronized method acquire?

    from the Java Tutorial for concurrency programming:
    " When a thread invokes a synchronized method, it automatically acquires the intrinsic lock _for that method's object_ and releases it when the method returns. The lock release occurs even if the return was caused by an uncaught exception. "
    what exactly does this mean?
    do synchronized methods acquire the monitors for objects of type: java.lang.reflection.Method
    please consider this code:
    public class Foo {
      private int counter = 0;
      public synchronized void incriment() { counter++; }
      public synchronized void decriment() { counter--; }
    Foo f = new Foo();
    Class[] sig = new Class[0];
    Method m = f.getClass().getMethod("incriment", sig);
    // ok. so "m" is the relevant method object.
    f.incriment(); // <-- is the monitor for "m" ,
                          // or the monitor for "f", acquired?
    .......my reading of the Concurrency Tutorial is that synchronized methods use the monitors of java.lang.reflection.Method objects?
    and thus, Foo is not thread safe, right?
    however, this simple change makes Foo thread-safe?
    public class Foo {
      private volatile int counter = 0; // "volatile"
      public void incriment() { counter++; }
      public void decriment() { counter--; }
    }thanks.
    Edited by: kogose on Feb 23, 2009 7:13 PM

    tensorfield wrote:
    jverd wrote:
    tensorfield wrote:
    kogose wrote:
    what exactly does this mean?It means you're complicating things.
    If a method is synchronized, it is. You don't need to go beyond that. The method is synchronized.Not true. You have to know what it means for a method to be synchronized. Often people come in with the erroneous impression that it somehow prevents you from using or accessing the object in any other thread.It's very simple. If a synchronized method is called at the same time from many threads only one call will be executed at a time. The calls will be lined up and performed one after the other in sequence.
    AND because synchronization is on a per object basis, when one synchronized method is being called from one thread, all synchronized methods of that same object are blocked for calling from other threads.
    Simple as that.No, it's not that simple, and as stated, that is not correct. In particular, you didn't mention that for an instance method, all the various threads have to be trying to call instance methods on the same object in order for execution to be sequential.
    You really can't understand Java's syncing without understanding how it relates to locks, and what it means for a method to be synchronized in terms of which lock it acquires.
    Edited by: jverd on Feb 25, 2009 2:47 PM

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

  • Use of final keyword on methods arguements ?

    Hi All,
    Just say I have an input arguement for a method which is an int. If I wanted to access the value stored by the input arguement reference inside an anonymous class that is contained in the method one way would be to pass the input arguement reference to a instance variable of the class that contains the method and use that.
    // Declared at start of  class
    int arrayIndex = 0;
    methodName(nt inputNumber)
        arrayIndex = inputNumber;
        ActionListener task = new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                // Accessing here
                anArray[arrayIndex] = 100;
    }Just wondering, I used the final keyword on the the input arguement instead and then used the input arguement directly instead. It seemed to work ok. Is this good programming practice or are there some pitfalls to using this that I'm not aware of?
    (I don't need to change what the input arguement reference points to)
    // Alternate
    methodName(final int inputNumber)
        ActionListener task = new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                // Accessing here
                anArray[inputNumber)] = 100;
    }Regards.

    declaring it final guarantees that you will not change the value.Of course it does. That's what it's for. That's what it means. But you're only guaranteeing that to yourself. It doesn't form part of the interface contract so it's no use to anybody else. Which is the bigger picture.
    Whenever i use any anonymous classes i prefer to use the final variables as long as i dont need to change their values.No you don't 'prefer' it, you are forced to do that by the compiler.

  • As a new Macbook Pro user I was saddened to find that the feature of using keywords in iPhoto '11 does not allow showing same under each photo.  I understand this was available in earlier versions.  Any comments?

    As a new Macbook Pro user I was saddened to find that the feature of using keywords in iPhoto '11 does not allow showing same under each photo.  I understand this was available in earlier versions.  Any comments?

    Against TOU which you "agreed" to in order to post in these user to user forums.  If you want to "suggest" something to Apple, do so in the Product Feedback area.

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

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

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

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

  • How to use Synchronized method when creating our own controls

    I don't know how to use the synchronized method when creating our own activex like controls to speed up the application.

    [url http://java.sun.com/docs/books/tutorial/essential/threads/multithreaded.html] here you go 

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

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

Maybe you are looking for

  • Web Photo Gallery in CS4

    I know the Web Photo Gallery has been removed from PS CS4 and put into Bridge. However, I created a few templates I would like to keep. Is there any way besides using CS3 that I might do this in Bridge? Is there going to be a way in Bridge to create

  • Duplicate messages in Inbox

    In Macbook Pro, in Mail, I receive a duplicate message in the Inbox. Under the inbox file is another file labeled with my e-mail address. I only receive the one message in it. How do I stop getting duplicate messages in My Inbox?

  • I have a Photosmart 6510e that will only print after I shut printer off and then restart..

    After setting up my 6510e photosmart all computers are able to print ---laptop, netbook and my iPhone can eprint.  However, my desktop PC will only print once the printer sleeps (white light is dim) after I completely shut off the printer and then re

  • View Links and Associations

    hi all, What is the difference between view links which is based on associations and view links which is not based on associations? yours, Bassam

  • Inner join on four tables

    hi all, i am facing the problem with the inner join in the select query for 4 tables. can i use the inner join for tables in SAP 6.0 version, it is going to dump. here is my code SELECT DISTINCT apernr abegda aendda awagetype aamount acurrency