Trivial Lock Question - nested synchronized instance method call

Hi there. I have a question surrounding the following code block:
        public synchronized void bow(Friend bower)
            System.out.format("%s: %s has bowed to me!%n",
                    this.name, bower.getName());
            bower.bowBack(this);
        public synchronized void bowBack(Friend bower)
            System.out.format("%s: %s has bowed back to me!%n",
                    this.name, bower.getName());
        }If the bow method is invoked by the currently executing thread that has obtained the lock on the current instance and the
call "bower.bowBack()" is invoked, what happens? Is the lock released then obtained again by the current thread? or does it hold onto it since the method
"bowBack" is called within the method "bow"?
Thank you!
Regards

thank you as always mr. verdagen!
regards

Similar Messages

  • Question about synchronizing two methods...

    i have 2 methods:
    writeData() //method 1
    createNewDataFile() //method 2
    the main thread will be using method 1 quite frequently. In method 2, a separate thread will be waking up every 10 minutes or so and doing some maintenance on the file written to in method 1. So, when the thread is in method 2 i need method 1 to standby and wait. I also want the opposite, that when the main thread is in method 2 method 1 will stand by.
    Any help is appreciated!

    799454 wrote:
    So wait,
    i thought synchronized only worked on the actual methods where it is declared:Using the synchronized keyword obtains a lock. Each object has exactly one lock associated with it. Once a thread has obtained an object's lock, no other thread can obtain that lock (and hence cannot enter a sync block on that lock) until the first thread releases it by leaving its sync block or calling wait().
    so, you're saying that if i declare:
    synchronized method 1
    synchronized method 2
    then i have a single object with 2 synchronized methods, so if thread A is in EITHER of those methods, the other method will be locked as well?The method isn't "locked" per se, but yes, 1 object, 2 synced methods, if T1 is in either method, then T2 cannot enter either method.
    I strongly urge you to go through that tutorial and/or a book on Java concurrency, thoroughly.

  • Synchronized Instance Methods in Singleton Class

    If I've a TransactionManager class that's a singleton; meaning one manager handling clients' transaction requests, do I need to synchronize all of the instance methods within that singleton class?
    My understanding is that I should; otherwise, there's a chance of data corruption when one thread tries to update, but another thread tries to delete the same record at the same time.

    Let's say that you have a singleton that is handling
    the printing in a desktop application. This could be
    time consuming and it will not probably be used too
    often. What's time consuming about instantiating the object?
    On the other hand you could not say that it
    will never be used.Exactly. If that were so, why write it?
    In a web application, response time is much more
    important than initialization time (which can be
    easily ignored). Never ignored. It's just a question of when you want to pay.
    Web app as opposed to desktop app? Does response time not matter for them?
    In this case, of course, eager
    initialization makes much more sense.I'm arguing that eager initialization always makes more sense. Lazy for singletons ought to be the exception, not the norm.
    %

  • Non-synchronized client method calls

    hi there,
    i am having following scenario:
    methods provided in the remote interface of a stateful session bean are called by a remote client.. client is using multithreading. now these methods in stateful session forward method calls to a stateless session and then an entity using local interfaces. the point here is that the client only has one object of the stateful session ( obviously an object per user session)
    the problem is that when i call the methods on this object one by one it goes fine. but when in multithreaded client application one method is called by first thread and another by second at the same time, application crashes. and the server tells that client has tried to enter stateful session with different transaction context. does anybody have some idea to solve this problem without having the client to make synchronized calls.
    thanx in advance,
    ra4a

    Hi,
    The Container serializes calls to stateful session beans.And hence your application calling in a multithreaded environment will surely fail.This is because the state of the bean might be corrupt when calls are concurrent.And different applications servers might provide some way of overriding this behaviour..Surely weblogic has got one way..
    Sathya

  • Some question about  about remote method call!

    I am planning to write a program like this:
    in my local computer,I want to type some commands to let my remote computer to execute some programs and send back the results back to me.
    Is it some thing about the java.rmi??
    If I want to get started,how should I do.
    I shall show my warmly thanks to whom can give me some simple code examples.
    Thanks in advance!

    Sorry, I don't have any code examples available, but a good place to start is the RMI-tutorial:
    http://developer.java.sun.com/developer/onlineTraining/rmi/

  • What is a lock in a synchronized method ??

    Greetings,
    I have a synchronized reset method whose job is to reset every variable i am using in that class.. its a synchronized method so when i am doing the reset stuff, no other method in that class can update that variable. But someone told me i need to also put lock inside the reset method and check for the lock everywhere where i update those variables ( So that variable doesn't update itself and lose its value as reset would be resetting that variable.) How do i lock all these variables in that reset method and how do i check for the lock where i would be updating that variable.
    Example: Psedo code
    class {
    int a =0;
    int b = 0;
    method update {
    a = 5;
    method update1{
    b = 6;
    synchronized method reset{
    a =0;
    b = 0;

    javanewbie83 wrote:
    Greetings,
    I have a synchronized reset method whose job is to reset every variable i am using in that class.. its a synchronized method so when i am doing the reset stuff, no other method in that class can update that variable. But someone told me i need to also put lock inside the reset method and check for the lock everywhere where i update those variables ( So that variable doesn't update itself and lose its value as reset would be resetting that variable.) How do i lock all these variables in that reset method and how do i check for the lock where i would be updating that variable.You don't need to "check" for the lock. When you have a synchronized block or method, the synhcronized keyword tells the VM to stop executing that thread until it can attain the object's lock, then give the object's lock to that thread, and then take it back when the thread leaves the synchronized block (or calls wait()). It's all automatic.
    Note that you'll need to synchronize not only write access to the variable(s) in question, but read access also, in order to ensure that reader threads see the values written by writers.

  • Question: Possible to assemble a method call within a program?

    I am writing an interpreter for a school project. I would like to read all instructions into an array in the format PC: Instruction: arg1: arg2: destination:
    My question is can I assemble from the Instruction name, for instance, "sqrt", a method call to public int[][] sqrt(int[][] varValue, int x, int d)? Is that even possible?
    The challenge for me is, after having written all opcode instructions as methods, how do I call them after I read a text string? Is this even a good approach to algorithm design?
    Thank you for your input.

    Ebodee wrote:
    My question is can I assemble from the Instruction name, for instance, "sqrt", a method call to public int[][] sqrt(int[][] varValue, int x, int d)? Is that even possible?Sure.
    The challenge for me is, after having written all opcode instructions as methods, how do I call them after I read a text string? So you have an array of instructions, and you have a bunch of methods that implement the instructions, right?
    (BTW, are the instructions really like sqrt? Because a more normal assignment would probably have you implement instructions like add, increment, store, etc.)
    You could use reflection to get the methods, but that's kind of a hack and a cheat (because it diverges even further from an emulation -- it's harder to map meaningfully to hardware. (This is just my opinion of course.))
    What I'd suggest is to create an Opcode interface, with a method like "void invoke(Object... args)". Then create an implementation of that for each opcode. Put objects of those methods into a Map<String, Opcode>. Then you can look them up by name.
    Is this even a good approach to algorithm design?You're not really designing an algorithm here. It sounds like you're building an virtual processor of some kind. Quicksort is an algorithm. A simulation of a computer is an application.
    Whether it's a good approach... it depends a lot on the assignment. At some point you're going to have to relinquish behavior from the emulation and let Java do some kind of bare computation. (You can't emulate everything; at some point lower-level software or hardware has to handle the semantics of what's going on.) The answer to your question depends on what level does the teacher want you to stay on. Can you write a sqrt function in Java and invoke it from your emulator, or do you have to write sqrt in the machine code of the emulator?

  • How to call a instance method without creating the instance of a class

    class ...EXCH_PRD_VERT_NN_MODEL definition
    public section.
      methods CONSTRUCTOR
        importing
          value(I_ALV_RECORDS) type ..../EXCH_VBEL_TT_ALV
          value(I_HEADER) type EDIDC .
      methods QUERY
        importing
          I_IDEX type FLAG
          i_..........
        returning
          value(R_RESULTS) type .../EXCH_VBEL_TT_ALV .
    Both methods are instance methods.
    But in my program i cannot created instance of the class unless i get the results from Query.
    I proposed that Query must be static, and once we get results we can create object of the class by pasing the result table which we get from method query.
    But i must not change the method Query to a static method.
    Is there any way out other than making method Query as static ?
    Regards.

    You can't execute any instance method without creating instance of the class.
    In your scenario, if you don't want to process your method of your class, you can check the instance has been created or not.
    Like:
    IF IT_QUERY IS NOT INITIAL.
      CRATE OBJECT O_QUERY EXPORTING......
    ENDIF.
    IF O_QUERY IS NOT INITIAL.
    CALL METHOD O_QUERY->QUERY EXPORTING....
    ENDIF.
    Regards,
    Naimesh Patel

  • A method call question.

    I am trying to check if leg1 is a positive integer, but I method call checkleg, and perform my if statement, but it will not return a 'valid = true' to my public static main. It is always false. please help!
    * TriangleTest.java
    * Created on October 3, 2007, 4:10 PM
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package triangletest;
    * @author Nate
    import java.util.Scanner;
    public class TriangleTest {
        /** Creates a new instance of TriangleTest */
        public TriangleTest() {
         * @param args the command line arguments
        public static void main(String[] args) {
            // TODO code application logic here
         System.out.println ("**Triangle Validation Tool**");
         int leg1 = 0;
         int leg2 = 0;
         int leg3 = 0;
         int sumOfLegs;
         int count = 0;
         Boolean validIs = false;
         Boolean valid = false;
         Scanner input = new Scanner (System.in);
            System.out.println("Please enter the length of leg #1:");
            leg1 = input.nextInt();
            checkleg (leg1);
            System.out.println(valid);
            System.out.println("Please enter the length of leg #2:");
            leg2 = input.nextInt();
            System.out.println("Please enter the length of leg #3:");
            leg3 = input.nextInt();
            sumOfLegs = leg1+leg2+leg3;
            if (sumOfLegs != 180)
                System.out.println("Sorry, legs of lengths " + leg1+ ", "
                        + leg2+ ", and " + leg3 + " do NOT form a triangle!");
            else
                System.out.println("Congrats!");
        public static Boolean checkleg (int leg1){
            Boolean valid = false;
            if (leg1>0){
            valid = true;
            System.out.println(valid);
        return valid;
        }}Thanks

    Yippee!! the code tag button is back!!
    Please see comments:
         Boolean validIs = false;  // probably want to use "boolean" not "Boolean"
         Boolean valid = false;  // ditto
         Scanner input = new Scanner (System.in);
            System.out.println("Please enter the length of leg #1:");
            leg1 = input.nextInt();
            checkleg (leg1); // see my previous post
            sumOfLegs = leg1+leg2+leg3;
            if (sumOfLegs != 180)  // I hope you will correct this logic.
                System.out.println("Sorry, legs of lengths " + leg1+ ", "
                        + leg2+ ", and " + leg3 + " do NOT form a triangle!");
            else
                System.out.println("Congrats!");
        public static Boolean checkleg (int leg1){
            // note that while your local "valid" variable has the same name as the class "valid"
            // variable, they are both different variables and changing one will NOT change the other.
            Boolean valid = false;
            if (leg1>0){
            valid = true;
            System.out.println(valid);
        return valid;
        }}

  • Calling Instance Method in a Global Class

    Hi All,
    Please can you tell me how to call a instance method created in a global class in different program.
    This is the code which I have written,
    data: g_cl type ref to <global class>.
    call method g_cl -> <method name>
    I am not able to create Create object <object>.
    It is throwing the error message " Instance class cannot be called outside...."
    Please can anybody help me..
    *Text deleted by moderator*
    Thanks
    Sushmitha

    Hi susmitha,
    1.
    data: g_cl type ref to <global class>.
    2.
    Create object <object>.
    3.
    call method g_cl -> <method name>.
    if still you are getting error.
    then first check that method level and visibility in se24.
    1.if  level is static you can not call it threw object.
    2. if visibility is protected or private then you can not  call it directly.
    If still you are facing same problem please paste the in this thread so that i can help you better.
    Regards.
    Punit
    Edited by: Punit Singh on Nov 3, 2008 11:54 AM

  • AJAX calling a servlet's synchronized doPost method

    Hi all. This problem has been bugging me for a week already and still no solution in sight...
    Anyway, buttons in a page I'm creating uses AJAX to call a servlet's synchronized doPost method. Once a button is clicked, the servlet calls another java class which does some back end processing. Once the called java program is finished running, the page is updated telling the user that the selected backend process has finished running. It works fine if I just run one backend process at a time...however, if try to run another backend process while the previous backend process is still running, even if the backend process is finished, the page doesn't get updated with the message informing the user that the job is finished. The page only gets updated once all the jobs have finished running. What I want to happen is that whenever a job gets finished, the page gets updated.

    Yeah, it has
    something to do with the threads. However, I had to
    synchronize the doPost method because if the doPost
    method isn't synchronized, running 2 or more back end
    processes simultaneously would result in the previous
    backend processes being terminated, only the last
    back end process would be run successfully.Yea! that's what I wanted to say! most of the time there are critical sections in your code when concurrency is there, you need to recognize them and synchronize only the critical sections.
    I don't think synchronizing the whole dopost method is a better way to deal with concurrency issues. It defeats the purpose of spawning a new thread for each request(it's my personal opinion, I may be wrong).
    But I got one contradiction from one member of sun forum, he says spawning thread from a servlet is not a good practice according to java EE specification. But I don't think there is any way out other than this, to deal with this scenario. I am waiting for further suggestions, so keep an eye on this thread:
    http://forum.java.sun.com/thread.jspa?threadID=5149048
    ~cheers~

  • How to call Instance Methods and set property values in BAPI?

    In Project systems, for the three business objects viz.
    Network, ProjectDefinition and WBS, there are two kinds of methods which are available : class methods and instance methods. We have tried calling some instance methods, for instance, BAPI_PROJECTDEF_GETDETAIL to get details pertaining to a project. While importing this BAPI, it shows two elements for mapping i.e. Current Internal Project(string) and Current External Project(string). We supplied these values for an existing project. Upon running this call through an XML client at our end, it
    returned an error "Module Unknown Exception". This general message is present on every instance method thus far. Upon searching in BAPI Explorer for Project System->ProjectDefinition->GetDetail, we found that this BAPI didn't take any input parameter.
    Following message was displayed in BAPI Exlorer for this BAPI:
    "... Obligatory import parameters are the external and internal keys CURRENTEXTERNALPROJE and CURRENTINTERNALPROJE of the project definition.The system reads parameters contained in the structure
    BAPI_PROJECT_DEFINITION_EX ..."
    i) How to supply the values of Obligatory import parameters.
    ii) What are the possible causes of this exception.
    iii) How to call an instance method. We are using same mechanism for calling class as well as instance methods so far, we have been to call only class level methods successfully. Is there anything special that we
    need to do to call instance methods.

    Hi,
    what version is the SAP PS running?  If WebAs or higher,  create an inbound synch interface containing your two parameters in the request structure and as many as you require in your response structure.  Generate an Inbound ABAP proxy, where you can plug in some code, i.e. create and instantiate an object of the required type and make the call to the BAPI.
    If SAP PS on lower than WebAs, then create a wrapper function module and make it RFC enabled.  Then plug your code in here and do the same thing.
    Watch out for commits!
    Cheers,
    Mark

  • How do I 'call' external instance methods?

    I want to send a message from a Controller to another Class  to execute a method.  Inside the controller, I typed my message:     
                    [[MemoryContent]  PopulateMemory];
    What I think I am doing here is telling it to go to the MemoryContent class and execute the method called PopulateMemory.  The compiler insists that I make PopulateMemory into a class method.  But when I do that, I cannot deal with the instance methods and instance variables that I need.  What am I missing?

    Assuming you are following recommended Cocoa naming conventions, the fact that MemoryContent has an initial cap means it is a class, not an instance of a class. So the compiler error is correct. If you want to use an instance method, first create an instance of the class, then call the method on the instance.
    Your method name PopulateMemory should probably not have an initial cap.
    So you would typically see something like this.
    MemoryContent *memoryContent = [[MemoryContent alloc] init];
    [memoryContent populateMemory];
    Of course if the class instance already exists, don't create another one. Instead get a reference to the existing instance.

  • Question about method calling (Java 1.5.0_05)

    Imagine for example the javax.swing.border.Border hierarchy.
    I'm writing a BorderEditor for some gui builder, so I need a function that takes a Border instance and returns the Java code. Here is my first try:
    1 protected String getJavaInitializationString() {
    2     Border border = (Border)getValue();
    3     if (border == null)
    4         return "null";
    5
    6     return getCode(border);
    7 }
    8
    9 private String getCode(BevelBorder border) {...}
    10 private String getCode(EmptyBorder border) {...}
    11 private String getCode(EtchedBorder border) {...}
    12 private String getCode(LineBorder border) {...}
    13
    14 private String getCode(Border border) {
    15     throw new IllegalArgumentException("Unknown border class " + border.getClass());
    16 }This piece of code fails. Because no matter of what class is border in line 6, this call always ends in String getCode(Border border).
    So I replaced line 6 with:
    6     return getCode(border.getClass().cast(border));But with the same result. So, I try with the asSubClass() method:
    6     return getCode(Border.class.asSubClass(border.getClass()).cast(border));And the same result again! Then i try putting a concrete instance of some border, say BevelBorder:
    6     return getCode(BevelBorder.class.cast(border));Guess what! It worked! But this is like:
    6     return getCode((BevelBorder)border);And I don't want that! I want dynamic cast and correct method calling.
    After all tests, I give up and put the old trusty and nasty if..else if... else chain.
    Too bad! I'm doing some thing wrong?
    Thank in advance
    Quique.-
    PS: Sorry about my english! it's not very good! Escribo mejor en espa�ol!

    Hi, your spanish is quite good!
    getCode(...) returns the Java code for the given border.
    So getCode(BevelBorder border) returns a Java string that is something like this "new BevelBorder()".
    I want Java to resolve the method to call.
    For example: A1, A2 and A3, extends A.
    public void m(A1 a) {...}
    public void m(A2 a) {...}
    public void m(A3 a) {...}
    public void m(A a) {...}
    public void p() {
        A a = (A)getValue();
        // At this point 'a' could be instance of A1, A2 or A3.
        m(a); // I want this method call, to call the right method.
    }This did not work. So, i've used instead of m(a):
        m(a.getClass().cast(a));Didn't work either. Then:
        m(A.class.asSubClass(a.getClass()).cast(a));No luck! But:
        m(A1.class.cast(a)); // idem m((A1)a);Woks for A1!
    I don't know why m(A1.class.cast(a)) works and m(a.getClass().cast(a)) doesn't!
    thanks for replying!
    Quique

  • [svn] 4171: Nested exception handlers in an instance method: fix arg0 ( the activation record).

    Revision: 4171
    Author: [email protected]
    Date: 2008-11-23 18:09:10 -0800 (Sun, 23 Nov 2008)
    Log Message:
    Nested exception handlers in an instance method: fix arg0 (the activation record).
    Modified Paths:
    flex/sdk/trunk/modules/asc/src/java/adobe/abc/GlobalOptimizer.java

    Revision: 4171
    Author: [email protected]
    Date: 2008-11-23 18:09:10 -0800 (Sun, 23 Nov 2008)
    Log Message:
    Nested exception handlers in an instance method: fix arg0 (the activation record).
    Modified Paths:
    flex/sdk/trunk/modules/asc/src/java/adobe/abc/GlobalOptimizer.java

Maybe you are looking for