Synchronized Static & Non Satatic methods

Is synchronized static method acquire lock ? I have wriietn a code in which i synchronized a static & non static(instance) method. but statc method call is not acquiring a lock.
If its not posible then there is a chance of corruption of static data.
plz inform me
my code is given below
public class TestThread{
     private static int i=0;
     public synchronized static void m1(){
          System.out.println("1 Static M1 \t");     
          i++;     
          try{Thread.sleep(10000);}
          catch(Exception e){e.printStackTrace();}
          System.out.println("2 Static M1 \t");
     public synchronized void m2(){
          System.out.println("1 Static M2 \t");
          i++;
          try{Thread.sleep(10000);}
          catch(Exception e){e.printStackTrace();}
          System.out.println("2 Static M2 \t");
     public static void main(String[] args){
          new Thread(){
               public void run(){     
                    TestThread.m1();               
          }.start();
     try{Thread.sleep(100);}
     catch(Exception e){e.printStackTrace();}
          new Thread(){
               public void run(){     
                    new TestThread().m2();               
          }.start();

Your example has two methods, both of which modify a static integer of the same class.
Both of your methods are synchronized - but - one is static and one isn't. A synchronized static method aquires the 'lock' of the class, where as a non-static method aquires the 'lock' of the object.
For this reason, your two method calls are locking on different objects and so they may be invoked by different threads executing at the 'same time'.
Just to clarify, you can see this:
class Test {
  private static int i = 0;
  public static synchronized modifyStatic() {
    ++i;
  public synchronized modify() {
    ++i;
}As being this:
class Test {
  private static int i = 0;
  public static modifyStatic() {
    synchronized(Test.class) {
        ++i; 
  public modify() {
    synchronized(this) {
      ++i;
}So, as you can see from above, the two locks aquired are not the same.
Dave

Similar Messages

  • Synchronized static method -is there a problem?

    Hi.
    I'm facing a problem. I have a common java class that is used by many applications. Class is in a jar file and is in server's shared library. And every applications in the server used it.
    Methods are declared static but not synchronized static. Class itself is not static. I have found that sometimes right after server is restarted and applications are using this class, method return values are mixed up or method behaviour is strange. I havent able to repeat this problem when testing with just one application.
    Is the problem static method and when using under one classloader (in shared lib) probelm occurs? So if i declare it static synchronized, does that solve my problem?

    Ok. But is it still risk to use static classes or
    static methods/fields in class that are shared with
    multiple applications ie. in servers shared library?That's a big fat YES.
    I suspect that you might benefit from investing a couple of hours in the "concurrency" tutorial
    http://java.sun.com/docs/books/tutorial/essential/concurrency/

  • Synchronized static method???

    Hi!
    What does it means "synchronized static" method? What object in this case has a lock monitor?
    class MyClass  {
    public synchronized static someMethod() {
    }Is it the equivalent to:
    synchronized ( MyClass.class ) {
    Anton

    The JVM creates a Class object when the class is loaded (When it is used for the first time) the
    JVM creates one instance of Class for each class that is loaded, thus a class itself has a moniter
    which a thread can gain ownership of.

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

  • Can i call non -abstract method in abstract class into a derived class?

    Hi all,
    Is it possible in java to call a non-abstract method in a abstact class from a class derived from it or this is not possible in java.
    The following example will explain this Ques. in detail.
    abstract class A
    void amethod()
    System.out.println(" I am in Base Class");
    public class B extends A
    void amethod()
    System.out.println(" I am in Derived Class");
    public static void main (String args[])
    // How i code this part to call a method amathod() which will print "I am in Base Class
    }

    Ok, if you want to call a non-static method from a
    static method, then you have to provide an object. In
    this case it does not matter whether the method is in
    an abstract base class or whatever. You simply cannot
    (in any object oriented language, including C++ and
    JAVA) call a nonstatic method without providing an
    object, on which you will call the method.
    To my solution with reflection: It also only works,
    if you have an object. And: if you use
    getDeclaredMethod, then invoke should not call B's
    method, but A's. if you would use getMethod, then the
    Method object returned would reflect to B's method.
    The process of resolving overloaded methods is
    performed during the getMethod call, not during the
    invoke (at least AFAIK, please tell me, if I'm wrong).You are wrong....
    class A {
        public void dummy() {
             System.out.println("Dymmy in A");
    class B extends A {
         public void dummy() {
              System.out.println("Dymmy in B");
         public static void main(String[] args) throws Exception {
              A tmp = new B();
              Class clazz = A.class;
              Method method = clazz.getDeclaredMethod("dummy", null);
              method.invoke(tmp, null);
    }Prints:
    Dymmy in B
    /Kaj

  • Static/non-static

    Hi!
    I've read some docs, but can't seem to find an adequate answer to this:
    Why can't a non-static field or method be referenced by a static method and vice versa?
    What's the problem exactly?
    Thanks in advance!

    Wow, I've seemed to have touched on something here. I guess I should clarify what I mean.
    deenen is correct in what I was talking about. In that when you have a static instance variable the memory space is shared by all instances of the class.
    Now if it is good practice or style to do such a thing that is another matter. The talk about how you can't change a static variable is incorrect. The static keyword only means that there is no need for an explicit parameter (or implicit, I always mess the two up). Because it implies the keyword "this".
    The keyword final is used to make it so that you can not change a variable once it has been initialized.
    I have used this static instance variable to my advantage only in debugging objects. When I have lots of objects and they have to all keep the same state I sometimes put a static variable in the class and keep testing it to make sure that the state never changes. Probably bad practice, but like I said, only for debugging. That way I can tell usually when the state changed (which is good in threaded apps). But not which object it was changed on.

  • Can't make static reference to method while it is static

    Hello, can somebody please help me with my problem. I created a jsp page wich includes a .java file I wrote. In this JSP I called a method in the class I created. It worked but when I made the method static and adjusted the calling of the method it started to complain while i didnt make an instance of the class. the error is:Can't make static reference to method
    here is the code for the class and jsp:
    public class PhoneCheckHelper {
    public static String checkPhoneNumber(String phoneNumber) {
    String newPhoneNumber ="";
    for(int i=0; i<phoneNumber.length(); i++) {
    char ch = phoneNumber.charAt(i);
    if(Character.isDigit(ch)) {
    newPhoneNumber += String.valueOf(ch);
    return newPhoneNumber;
    <html>
    <head>
    <title>phonecheck_handler jsp pagina</title>
    <%@page import="java.util.*,com.twofoldmedia.text.*, java.lang.*" %>
    </head>
    <body>
    <input type="text" value="<%= PhoneCheckHelper.checkPhoneNumber(request.getParameter("phonenumberfield")) %>">
    </body>
    </html>

    Go over to the "New to Java" forum where that message is frequently explained. Do a search if you don't see it in the first page of posts.

  • Can't make static reference to method

    hi all,
    pls help me in the code i'm getting
    " can't make static reference to method....."
    kindly help me
    the following code gives the error:
    import java.rmi.*;
    import java.rmi.Naming;
    import java.rmi.RemoteException;
    import java.io.*;
    import java.io.IOException;
    import java.io.LineNumberReader;
    public class client
    static String vcno;
    static String vpin;
    static String vamt;
    static String vordid;
    static String vptype;
    //static String vreq;
    static String vreq = "1";
    static String vorgid;
    static String vm1;
    static String vs1;
    static String vqty1;
    static String vm2;
    static String vs2;
    static String vqty2;
    static String vm3;
    static String vs3;
    static String vqty3;
    static String vm4;
    static String vs4;
    static String vqty4;
    public static void main(String args[])
    try
    ServerIntf serverintf=(ServerIntf)Naming.lookup("rmi://shafeeq/server");
    int c;
    StringBuffer sb;
    FileReader f1=new FileReader("c:/testin.txt");
    sb=new StringBuffer();
    int line=0;
    while ((c=f1.read())!=-1) {
    sb.append((char)c);
    LineNumberReader inLines = new LineNumberReader(f1);
    String inputline;
    String test;
    while((inputline=inLines.readLine())!=null)
    line=inLines.getLineNumber();
    switch(line)
    case 1: {
    vcno = inLines.readLine();
    System.out.println(vcno);
    case 2: {
    vpin = inLines.readLine();
    System.out.println(vpin);
    case 3: {
    vptype = inLines.readLine();
    System.out.println(vptype);
    case 4: {
    vamt = inLines.readLine();
    System.out.println(vamt);
    case 5: {
    vordid = inLines.readLine();
    System.out.println(vordid);
    case 6: {
    vorgid = inLines.readLine();
    System.out.println(vorgid);
         case 7: {
    vm1 = inLines.readLine();
    System.out.println(vm1);
         case 8: {
    vs1 = inLines.readLine();
    System.out.println(vs1);
         case 9: {
    vqty1 = inLines.readLine();
    System.out.println(vqty1);
         case 10: {
    vm2 = inLines.readLine();
    System.out.println(vm2);
         case 11: {
    vs2 = inLines.readLine();
    System.out.println(vs2);
    case 12: {
    vqty2 = inLines.readLine();
    System.out.println(vqty2);
    case 13: {
    vm3 = inLines.readLine();
    System.out.println(vm3);
         case 14: {
    vs3 = inLines.readLine();
    System.out.println(vs3);
    case 15: {
    vqty3 = inLines.readLine();
    System.out.println(vqty3);
    case 16: {
    vm4 = inLines.readLine();
    System.out.println(vm4);
    case 17: {
    vs4 = inLines.readLine();
    System.out.println(vs4);
    case 18: {
    vqty4 = inLines.readLine();
    System.out.println(vqty4);
    f1.close();
    FileWriter f2=new FileWriter("c:/testout.txt");
    String t;
    t=ServerIntf.add(vcno,vpin,vamt,vordid,vptype,vreq,vorgid,vm1,vs1,vqty1,vm2,vs2, vqty2,vm3,vs3,vqty3,vm4,vs4,vqty4);
    String str1 = " >>";
    str1 = t + str1;
    f2.write(str1);
    System.out.println('\n'+"c:/testout.txt File updated");
    f2.close();
    catch(Exception e)
    System.out.println("Error " +e);

    Yes, ServerIntf is the interface type. The instance serverIntf. You declared it somewhere at the top of the routine.
    So what you must do is call t=serverIntf.add(...)This is probably just a mistype.

  • Non-abstract methods in a Abstract class

    Abstract Class can contain Non-abstract methods.
    and Abstract Classes are not instantiable as well
    So,
    What is the purpose of Non-abstract methods in a Abstract class.
    since we can't create objects and use it
    so these non-abstract methods are only available to subclasses.
    (if the subclass is not marked as abstract)
    is that the advantage that has.(availability in subclass)
    ??

    For example, the AbstractCollection class (in
    java.util) provides an implementation for many of the
    methods defined in the Collection interface.
    Subclasses only have to implement a few more methods
    to fulfill the Collection contract. Subclasses may
    also choose to override the AbstractCollection
    functionality if - for example - they know how to
    provide an optimized implementation based on
    characteristics of the actual subclass.Another example is the abstract class MouseAdapter that implements MouseListener, MouseWheelListener, MouseMotionListener, and that you can use instead of these interfaces when you want to react to one or two types of events only.
    Quoting the javadocs: "If you implement the MouseListener, MouseMotionListener interface, you have to define all of the methods in it. This abstract class defines null methods for them all, so you can only have to define methods for events you care about."

  • TS1292 i can't find options of none payment method in my account

    i can't find options of none payment method in my account

    There are two possible drivers, HP Deskjet 5550 (HPA) (HP) and HP Deskjet 5550 (HPA) (Microsoft).  Either of these should work, I think the HP one is a bit newer.  What is the nature of "not working"?  You could also use the HP Deskjet 990 driver.
    The HP Windows 7 Printer Install Wizard at http://www.hp.com/go/tools may help automatically install the proper driver.
    Bob Headrick,  HP Expert
    I am not an employee of HP, I am a volunteer posting here on my own time.
    If your problem is solved please click the "Accept as Solution" button ------------V
    If my answer was helpful please click the "Thumbs Up" to say "Thank You"--V

  • I want to change my account payment method to none and I do not have a credit card yet.Plus, iTunes gave a message saying that I need to review my account and when I go there,the none payment method is hidden.

    I want to change my account payment method to none and I do not have a credit card yet.Plus, iTunes gave a message saying that I need to review my account and when I go there,the none payment method is hidden.

    Assuming that you want help and that you aren't just copying-and-pasting that thread's title and posting a link to it, then have you tried the steps on the post that I linked to in my first reply on that thread ?
    If you don't get the 'none' option when trying those instructions then you will need to enter credit card details before you will be able to use the account - when you've entered credit card details you should get the 'none' option and be able to remove your card details.
    Or you can create a new account, and follow, exactly, the steps on this page when creating it' : http://support.apple.com/kb/HT2534

  • Name space conflict between static and instance method

    Hello,
    there seems to be a very unfortunate name space conflict between static and instance method name. Consider:
    static String description() that should return a description of a class.
    String description() that should return a description of an instance.
    That seems to confuse the compiler. How come? Static and instance methods don't have anything to get confused about.
    Thanks for any insights :-)

    Umm...jeez.
    It's not a bug, it's the way it's supposed to be.
    Since a static method can be called the same way an instance method
    A instance = new A();
    A.staticMethod();
    instance.staticMethod();it's not allowed.
    Also in the class, you can call
    public void myMethod() {
          instanceMethodInClass();        // You don't need this, it's superfluous
          staticMethodInClass();          // You don't need the class name.
    }If you didn't understand, then just accept the fact that it is so. Some day you'll understand it.

  • A basic question about static variables and methods

    What would be the effects if I declare lots of static variables and static methods in my class?
    Would my program run faster?
    Would the class take more memory spaces? (If so, how do I estimate an appropriate number of variabls and methods to be declared static?)
    Thank you @_@

    when you declare a static var the var isn't created for every instance of the class, it just "live" in the class
    when you declare a static method is the same, so if you have:
    class MyClass
    static int myMethod()
    //Method work
    you dont need to have a instance of the class to call myMethod, you can do such things like this.
    int value = Myclass.myMethod();
    if myMethod isn't static you can't do this.. so, if
    class MyClass
    int myMethod()
    //Method work
    you CAN'T call
    int value = MyClass.myMethod();
    instead, you have to write
    MyClass m;
    m = new MyClass();
    value = m.myMethod();

  • Load Akamai plugin example using Static plugin loading method

    Hi,
    I want to load Akamai plugin example using Static plugin loading method. For that, I passed "com.akamai.osmf.AkamaiBasicStreamingPluginInfo" as a class defination, but I got error stating, ReferenceError: Error #1065: Variable AkamaiBasicStreamingPluginInfo is not defined.
    Makjosh once sent a post that the title was "Getting an error while loading the plugin using static plugin load method". I then follow the solution. But how can I add the dependent project(Flex/AS Build Path -> Library Path -> Add Project). As a result, I do not find the AkamaiBasicStreamingPlugin project only having the NetMocker project and the StrobeUnit project in it.
    So I try to link the AkamaiBasicStreamingPlugin project use the following method(project properties->Project References->select "AkamaiBasicStreamingPlugin"), it still causes the same error.
    Please help me.
    Thanks.

    Hi,
    A couple of things to look at:
    1) Make sure you have the import statement in your project:
                import com.akamai.osmf.AkamaiBasicStreamingPluginInfo;
    2) Make sure you add the AkamaiBasicStreamingPlugin folder to your Flex Build Path (right click project, select "properties", then "Flex Build Path", in "Source Path" you need to add the plugin folder).
    3) If you are still getting Error #1065, you can try a trick where you force the swf compiler to pull in the class:
                private static const loadTestRef:AkamaiBasicStreamingPluginInfo = null;
    Now you should be able to use getDefinitionByName to load the plugin:
                    var pluginResource:IMediaResource;
                    var pluginInfoRef:Class = flash.utils.getDefinitionByName(className) as Class;
                    pluginResource = new PluginClassResource(pluginInfoRef);
                    pluginManager.addEventListener(PluginLoadEvent.PLUGIN_LOADED, onPluginLoaded);
                    pluginManager.addEventListener(PluginLoadEvent.PLUGIN_LOAD_FAILED, onPluginLoadFailed);
                    pluginManager.loadPlugin(pluginResource);
    Hope that helps,
    - charles

  • Identifying non-public methods

    Is there any way for an object to idenify its own non-public methods (getMethods() returns only those methods that are declared public)?

    getDeclaredMethods() - I believe this might do what you want. It throws a SecurityException, but I'm not sure exactly under what circumstances! Oh, and it doesn't return methods defined on any superclasses.

Maybe you are looking for

  • Demand is not getting updated in MD04

    Hi Team, we are facing strange issue for an particular plant. Issue :-In MD04 forecast is not getting reduced after doing PGI. For this MTO  scenario when we are creating outbound delivery requirement of quantity is getting generated in MD04 but afte

  • Is there a way to open Pages 09 documents in Yosemite?

    Hi. I upgraded to Yosemite last year. But today I realized I needed to open some Pages 09 documents. They won't open in the newer, latest version of Pages. I can view the contents of the documents in the Finder via Cover Flow - so I think it's crazy

  • How do i clean start up disk

    I am using Lion 10.7.4 adn would like to knnow how to clean my start up disk as the system is taking to long to open.

  • How to check file name in local c drive and run exe file

    Hi All, I'm newbie user in action script. How can i check sepecific file name in local c:\ drive and if file doesn't exist in local drive download from server and run and if exist go to frame ..... . Please help to me. Thanks,

  • How do I set the "hide selection" key back to CMD+H?

    When I installed Photoshop CS6 on my Mac, it gave me the option of using the keys CMD+H to hide Photoshop.  Without thinking I said "Yes"  Duh!  What was I thinking.  I always use CMD+H to hide selections!  I have been looking around in the prefs, bu