Synchronized statements and deadlock

I've been reading on the tutorial about synchronized statements:
http://java.sun.com/docs/books/tutorial/essential/concurrency/locksync.html
...and I don't understand when it says, about the following example:
    public void addName(String name) {
        synchronized(this) {
            lastName = name;
            nameCount++;
        nameList.add(name);
    }"In this example, the addName method needs to synchronize changes to lastName and nameCount, but also needs to avoid synchronizing invocations of other objects' methods. (Invoking other objects' methods from synchronized code can create problems that are described in the section on Liveness.) "
Why do I need to avoid synchronizing invocations of nameList object? When thread1 gets an instrinsic lock to the instance of this class, does it also get a lock on the nameList object?
I suppose they're saying that I should avoid synchronizing invocations of nameList object to avoid deadlock, but I can't see how a deadlock would occur here.
I've read about deadlock but the example on the tutorial seams a different case to me because that example puts to objects crossing data between each other.
Another doubt is: in the deadlock example, which is found here
http://java.sun.com/docs/books/tutorial/essential/concurrency/deadlock.html
thread1 invokes synchronized method "bow" on object alphonse, while thread2 invokes that same method on object gaston. Does this garantee that the methods will not interleave? Doesn't it have to be the same object being used on both threads?
Quoting the same tutorial: "It is not possible for two invocations of synchronized methods on the same object to interleave."
Help appreciated on clarifying this.

>
If you use the first bit of code and make another block to synchronize on nameList then you could have another method that synchronizes inside on nameList and that could deadlock if it also needs to synchronize on this.
I'm still confused. If I had in MyClass
public void addName(String name) {
    synchronized(this) {
        lastName = name;
        nameCount++;
        nameList.add(name);
}which I understand is equivalent to
public void synchronize addName(String name) {
        lastName = name;
        nameCount++;
        nameList.add(name);
}and then I had
public void removeName(String name) {
    synchronized(this) {
        lastName = null;
        nameCount--;
        nameList.remove(name);
}then when thread1 invoked myClass.addName(someString) would acquire a lock on myClass and thread2, invoking myClass.removeName(someString) would have to wait for thread1 to conclude. It doesn't seam to be nothing wrong on this to me...
Please help.

Similar Messages

  • Question about synchronize() statement and thread scheduling?

    I have threads accessing a shared LinkedList in the main thread. I made use of the Collections.synchronizedList() to avoid concurrent modifications. one of the threads is a timer thread and it has a priority of 5 and the other threads are message reception threads and i made them of a lower priority just to allow the timer thread to be executed on time. According to the javaAPI, all iterations on the synchronized list should be done using synchronized(synchronizedListRef){} and this is what i do,
    The problem is even after setting the priority of the reception threads lower than the timer thread, the reception threads are sometimes executed more than once and the timer thread is delayed. Lets assume the situation where the timer reaches the point where it has to acquire the lock (the synchronized statement) and it discovers that the lock is already taken and it cant access the list because the other thread (of a lower priority) is iterating over it. shouldnt the higherpriority thread be executed after that the reception thread (that is blocking the timer thread) finishes its execution and release the lock (even if there are other reception thread waiting)??
    does the priority play a role when a thread is blocked?

    Asady wrote:
    I have threads accessing a shared LinkedList in the main thread. I made use of the Collections.synchronizedList() to avoid concurrent modifications. Make sure you explicitly sync around all iterations. Just using Collections.sync is not enough.
    The problem is even after setting the priority of the reception threads lower than the timer thread, the reception threads are sometimes executed more than once and the timer thread is delayed.There's no guarantee as to how priority will be interpreted. The scheduler implementation is free to do pretty much anything.
    As for how to solve your problem, you might want to look at java.util.concurrent.*, e.g. PriorityQueue. If the classes there don't give you just what you need, you may be able to build on them, or at least get ideas from them. Bottom line is that if you want a specific scheduling algorithm, you'll have to implement it yourself, since Threads' priority semantics are only very loosely specified by the JLS.

  • Documents remain in "To be synchronized" state

    Hi All,
    I have created an index and attached a data source to it. This datasource consists of 5 text documents.
    When I re-index the datasource, all 5 documents always remain in "To be synchronized" state. Repeated re-indexing is also of no use.
    I have flushed the queue a number of times, restarted the portal and trex instance and performed re-indexing. Yet, all these documents do not move from "To be synchronized" state at all.
    I am not able to figure out where the problem is.
    Any suggestions on this?
    Thanks in advance,
    Pavithra

    Hi All,
    We have found the solution. In the Queue parameters, the parameter "Initial Indexing Mode" was set to ON. On resetting it to Off, the documents were optimized and all of them are in OK state.
    Hope this answer helps those who might face the same problem.
    Regards,
    Pavithra

  • Problem changing VISA synchronous state

    This seems to be a bug.  Can I get a CAR number for this?
    http://forums.ni.com/t5/LabVIEW/Changing-VISA-Synchronous-state/m-p/2358338#M735511
    Trying to change VISA read/write synchronous state.
    LabVIEW Help says to right click on the node and select the mode you want (Synchronous I/O Mode).
    I right click on it, See that "Synchronous" is checked, and because it is easier or built into my mouse memory I just re-assert the click on and choose "Synchronous", except that when I do that, it changes it to Asynchronous.  It behaves as if any choosing of the Synchronous I/O Mode just toggles the state, instead of actually setting the state to what you chose.
    This does not seem logical to me.  Am I doing this right, or is there some other problem going on here?

    Hi Warren,
    I looked at the issue you have described and filed a CAR. The CAR number is 399613.
    Regards,
    Arham H
    Applications Engineer
    National Instruments

  • Changing VISA Synchronous state

    Trying to change VISA read/write synchronous state.
    LabVIEW Help says to right click on the node and select the mode you want (Synchronous I/O Mode).
    I right click on it, See that "Synchronous" is checked, and because it is easier or built into my mouse memory I just re-assert the click on and choose "Synchronous", except that when I do that, it changes it to Asynchronous.  It behaves as if any choosing of the Synchronous I/O Mode just toggles the state, instead of actually setting the state to what you chose.
    This does not seem logical to me.  Am I doing this right, or is there some other problem going on here?

    I see what you're saying.  Any click on either of the two pull-rights toggles the current selection.
    I will agree that the semantics of the menu could be better, but as a practical matter it's below my threshold
    The icon changes to include the watchface glyph when the node is set to asynch, so I only right-click on it when I want to change it.  And it's waaay better than back in the days of yore, when it was a global app preference (syncVISA=TRUE, IIRC).
    Dave
    David Boyd
    Sr. Test Engineer
    Philips Respironics
    Certified LabVIEW Developer

  • Error in updating OBNK Table ( Bank Statements and Reconciliations,Manual)

    PLease advise ,
    Bank Statements and Reconciliations,Manual Reconciliation
    Client is receiving the following message:
    Error in updating OBNK Table
    Edited by: Philip Eller on May 20, 2008 9:03 AM

    Hi Darpal Thiarha,
    Please kindly refer to note 1132591 and note 1128677 to see if these are relevant to this issue. Upgrading to  2007A PL15 or above may avoid such issues relevant with the error 'Error in updating OBNK Table'.
    Regards,
    Candice Ren
    SAP Business One Forums Team

  • DAX - IF statement and filters within calculated column

    Hi all,
    I've got a bit of a complex formula I'm trying to run, but I'm not quite there yet.  I don't know where/how/if I can place a filter within my IF statement for a calculated column due to so many variables.  I either get errors or wrong numbers. 
    Hope the following makes sense. 
    Here is my formula for the calculated column [Years Since Last Task]:
    =IF (ISBLANK([Last Task Date]) && ([Current Role]<>BLANK()), DIVIDE([Quarters],4), FLOOR(1. * ( today() - [Last Task Date]) / 365, 0.25))
    Problem:  I am getting "114.25" for Ken....but I want a blank result instead.  Meaning, I need to also filter out any name (row) who has a blank [Current Role].  How do
    I add a filter to this current formula?  Is one more step of filtering possible in this IF statement?  (Maybe I shouldn't use an IF statement, and try CALCULATE instead?)
    Below is the table 'Work' for you to see what's happening.
    Name
    Quarters
    Last Task Date
    Current Role
    Years Since Last Task
    John
    1
    1
    0.25
    Mike
    4
    2/7/2011
    3
    3
    Todd
    5
    4/20/2009
    4
    5
    Jeff
    9/1/2013
    3
    0.5
    Ken
    0
    114.25
    Steve
    2
    12/3/2011
    2
    2.25
    Nate
    2
    1/1/2014
    2
    0.25
    Greg
    1
    8/11/2013
    1
    0.5
    Ross
    4
    11/9/2010
    4
    3.25
    Hope all this made sense.  Let me know if you have any thoughts.
    Thanks,
    ~UG1

    you can use nested IF-statements here:
    =IF (ISBLANK([Current Role]),
    BLANK(),
    IF(ISBLANK([Last Task Date]),
    DIVIDE([Quarters],4),
    FLOOR(1. * ( today() - [Last Task Date]) / 365,0.25)
    hth,
    gerhard
    Gerhard Brueckl
    blogging @ http://blog.gbrueckl.at
    working @ http://www.pmOne.com

  • Closing Statements and ResultSets

    I just recently realized that you need to close Statements and ResultSets in order to avoid getting the "Too many cursors"-message.
    My question is:
    Do you need to close both Statements and ResultSets?
    - not that it's a problem...
    if so:
    Does it matter which one you close first?

    I usually place the stmt.close() code in my finally block, to ensure that the statement gets closed, even if a SQLException occurs during the query/update. The ResultSet does not explicitly have to be closed, ... it is automatically closed when the Statement is closed, or if a new query is run on the same statement.

  • JDBC: Closing Connection does it close statement and resultset

    In my application I am facing ORA-0100 Maximum open cursors exceeded problem. We are executing quite a few queries and stored procedures before we close the connection object. But in few places statements and resultsets are not closed. Can these be a problem? Shouldn't they be automatically closed when the connection is closed?
    We are executing this block of code in a loop.

    in few places statements and
    resultsets are not closed. Can these be a problem?Yes.

  • Urgent:Difference amount in customer a/c statement and customer ledger bal

    Currently I am facing a problem whererby the same customer  having the same variable - cutoff giviing  me 2 different sets of figure.
    1)Using the statement of account  - cutoff as at 31 Oct 07, gives me ending figure of  -$658,526.98 (Attached file for your reference)
    [2)Using the FBL5N - the same customer cutoff as at 31 Oct 07, gives me ending figure of -$658,629.98
    So the difference figure is 103. so where can i check exactly.
    I have checked with the details  from the 2 different report , everything is inside, but the total using the 2 report - statement and FBL5N gives 2 different total.

    Hello,
    The amount diff. fr Stat. to FBL5N due to some reasons:
    1. Customer statement may or may not have similar slection critieria to FBL5N
    2. Check once other selection while executing the statement
    Regards
    partha
    [email protected]

  • I need to know all the questions below.  I had to restore my computer to original state and now even if I sign on it won't let me sync my ipad or iphone.  the message is that it is synced to another library and it could wipe out my data on the ipad.

    I need to know all the questions below.  I had to restore my computer to original state and now even if I sign on it won't let me sync my ipad or iphone.  the message is that it is synced to another library and it could wipe out my data on the ipad.  Am I understanding correctly? I am running Windows 7 but have never had any problems.  Thanks

    You need iTunes on the computer. There is no iTunes for your phone. See:
    Locked Out, Forgot Lock or Restrictions Passcode, or Need to Restore Your Device: Several Alternative Solutions
    1. iOS- Forgotten passcode or device disabled after entering wrong passcode
    2. iPhone, iPad, iPod touch: Wrong passcode results in red disabled screen
    3. Restoring iPod touch after forgotten passcode
    4. What to Do If You've Forgotten Your iPhone's Passcode
    5. iOS- Understanding passcodes
    6. iTunes 10 for Mac- Update and restore software on iPod, iPhone, or iPad
    Forgotten Restrictions Passcode Help
    You will need to restore your device as New to remove a Restrictions passcode. Go through the normal process to restore your device, but when you see the options to restore as New or from a backup, be sure to choose New.
    Also, see iTunes- Restoring iOS software.

  • Questions on Xontrol--H​ow to update the state and data

    Hello, everyone. I am new to use the XControl. I don't understand how the program in the facade update the "state" and "Data" after we click the button. I cannot do that, please give me some help on the XControl.
    My vi is in the attachment.
    Message Edited by McArthur on 03-24-2010 02:19 AM
    Working...
    Attachments:
    Button.zip ‏51 KB

    McArthur wrote: Now I understand the reason why the state can not update, because I didn't do as TCPlomp mentioned. It seems working now....
     I mentioned this too, however without a pretty picture.
    quote: 
    When you modify data or state, you need to update the action cluster to indicate that fact.
    McArthur wrote: The example is just a dummy, not really make sense.
    The example is really quite good and shows these things too as well as many other important points. Please try to fully understand it. 
    I would strongly advise you to also look at my other suggestions. You still haven't explained the purpose of the xcontrol. I am still curious.  
    LabVIEW Champion . Do more with less code and in less time .

  • Bind Variable in SELECT statement and get the value  in PL/SQL block

    Hi All,
    I would like  pass bind variable in SELECT statement and get the value of the column in Dynamic SQL
    Please seee below
    I want to get the below value
    Expected result:
    select  distinct empno ,pr.dept   from emp pr, dept ps where   ps.dept like '%IT'  and pr.empno =100
    100, HR
    select  distinct ename ,pr.dept   from emp pr, dept ps where   ps.dept like '%IT'  and pr.empno =100
    TEST, HR
    select  distinct loc ,pr.dept   from emp pr, dept ps where   ps.dept like '%IT'  and pr.empno =100
    NYC, HR
    Using the below block I am getting column names only not the value of the column. I need to pass that value(TEST,NYC..) into l_col_val variable
    Please suggest
    ----- TABLE LIST
    CREATE TABLE EMP(
    EMPNO NUMBER,
    ENAME VARCHAR2(255),
    DEPT VARCHAR2(255),
    LOC    VARCHAR2(255)
    INSERT INTO EMP (EMPNO,ENAME,DEPT,LOC) VALUES (100,'TEST','HR','NYC');
    INSERT INTO EMP (EMPNO,ENAME,DEPT,LOC) VALUES (200,'TEST1','IT','NYC');
    INSERT INTO EMP (EMPNO,ENAME,DEPT,LOC) VALUES (300,'TEST2','MR','NYC');
    INSERT INTO EMP (EMPNO,ENAME,DEPT,LOC) VALUES (400,'TEST3','HR','DTR');
    INSERT INTO EMP (EMPNO,ENAME,DEPT,LOC) VALUES (500,'TEST4','HR','DAL');
    INSERT INTO EMP (EMPNO,ENAME,DEPT,LOC) VALUES (600,'TEST5','IT','ATL');
    INSERT INTO EMP (EMPNO,ENAME,DEPT,LOC) VALUES (700,'TEST6','IT','BOS');
    INSERT INTO EMP (EMPNO,ENAME,DEPT,LOC) VALUES (800,'TEST7','HR','NYC');
    COMMIT;
    CREATE TABLE COLUMNAMES(
    COLUMNAME VARCHAR2(255)
    INSERT INTO COLUMNAMES(COLUMNAME) VALUES ('EMPNO');
    INSERT INTO COLUMNAMES(COLUMNAME) VALUES ('ENAME');
    INSERT INTO COLUMNAMES(COLUMNAME) VALUES ('DEPT');
    INSERT INTO COLUMNAMES(COLUMNAME) VALUES ('LOC');
    COMMIT;
    CREATE TABLE DEPT(
    DEPT VARCHAR2(255),
    DNAME VARCHAR2(255)
    INSERT INTO DEPT(DEPT,DNAME) VALUES ('IT','INFORMATION TECH');
    INSERT INTO DEPT(DEPT,DNAME) VALUES ('HR','HUMAN RESOURCE');
    INSERT INTO DEPT(DEPT,DNAME) VALUES ('MR','MARKETING');
    INSERT INTO DEPT(DEPT,DNAME) VALUES ('IT','INFORMATION TECH');
    COMMIT;
    PL/SQL BLOCK
    DECLARE
      TYPE EMPCurTyp  IS REF CURSOR;
      v_EMP_cursor    EMPCurTyp;
      l_col_val           EMP.ENAME%type;
      l_ENAME_val       EMP.ENAME%type;
    l_col_ddl varchar2(4000);
    l_col_name varchar2(60);
    l_tab_name varchar2(60);
    l_empno number ;
    b_l_col_name VARCHAR2(255);
    b_l_empno NUMBER;
    begin
    for rec00 in (
    select EMPNO aa from  EMP
    loop
    l_empno := rec00.aa;
    for rec in (select COLUMNAME as column_name  from  columnames
    loop
    l_col_name := rec.column_name;
    begin
      l_col_val :=null;
       l_col_ddl := 'select  distinct :b_l_col_name ,pr.dept ' ||'  from emp pr, dept ps where   ps.dept like ''%IT'' '||' and pr.empno =:b_l_empno';
       dbms_output.put_line('DDL ...'||l_col_ddl);
       OPEN v_EMP_cursor FOR l_col_ddl USING l_col_name, l_empno;
    LOOP
        l_col_val :=null;
        FETCH v_EMP_cursor INTO l_col_val,l_ename_val;
        EXIT WHEN v_EMP_cursor%NOTFOUND;
          dbms_output.put_line('l_col_name='||l_col_name ||'  empno ='||l_empno);
       END LOOP;
    CLOSE v_EMP_cursor;
    END;
    END LOOP;
    END LOOP;
    END;

    user1758353 wrote:
    Thanks Billy, Would you be able to suggest any other faster method to load the data into table. Thanks,
    As Mark responded - it all depends on the actual data to load, structure and source/origin. On my busiest database, I am loading on average 30,000 rows every second from data in external files.
    However, the data structures are just that - structured. Logical.
    Having a data structure with 100's of fields (columns in a SQL table), raise all kinds of questions about how sane that structure is, and what impact it will have on a physical data model implementation.
    There is a gross misunderstanding by many when it comes to performance and scalability. The prime factor that determines performance is not how well you code, what tools/language you use, the h/w your c ode runs on, or anything like that. The prime factor that determines perform is the design of the data model - as it determines the complexity/ease to use the data model, and the amount of I/O (the slowest of all db operations) needed to effectively use the data model.

  • Capture all SQL statements and archive to file in real time

    Want to Capture all SQL statements and archive to file in real time?
    Oracle Session Manager is the tool just you need.
    Get it at http://www.wangz.net
    This tools monitor how connected sessions use database instance resources in real time. You can obtain an overview of session activity sorted by a statistic of your choosing. For any given session, you can then drill down for more detail. You can further customize the information you display by specifying manual or automatic data refresh, the rate of automatic refresh.
    In addition to these useful monitoring capabilities, OSM allows you to send LAN pop-up message to users of Oracle sessions.
    Features:
    --Capture all SQL statement text and archive to files in real time
    --Pinpoints problematic database sessions and displays detailed performance and resource consumption data.
    --Dynamically list sessions holding locks and other sessions who are waiting for.
    --Support to kill several selected sessions
    --Send LAN pop-up message to users of Oracle sessions
    --Gives hit/miss ratio for library cache,dictionary cache and buffer cache periodically,helps to tune memory
    --Export necessary data into file
    --Modify the dynamic system parameters on the fly
    --Syntax highlight for SQL statements
    --An overview of your current connected instance informaiton,such as Version, SGA,License,etc
    --Find out object according to File Id and Block Id
    Gudu Software
    http://www.wangz.net

    AnkitV wrote:
    Hi All
    I have 3 statements and I am writing some thing to a file using UTL_FILE.PUT_LINE after each statement is over. Each statement takes mentioned time to complete.
    I am opening file in append mode.
    statement1 (takes 2 mins)
    UTL_FILE.PUT_LINE
    statement2 (takes 5 mins)
    UTL_FILE.PUT_LINE
    statement3 (takes 10 mins)
    UTL_FILE.PUT_LINE
    I noticed that I am able to see contents written by UTL_FILE.PUT_LINE only after statement3 is over, not IMMEDIATELY after statement1 and statement2 are done ?
    Can anybody tell me if this is correct behavior or am I missing something here ?Calling procedure must terminate before data is actually written to the file.
    It is expected & correct behavior.

  • Session state and browser cache - Back button problem

    Hi all,
    I have a problem (and unless I'm missing something I think we all do) with session state and use of the browser's Back button. I really hope I'm just being dumb...
    Background scenario:
    Page P has a sidebar list allowing the user to select what content is displayed (e.g. 'stuff relating to X, Y or Z' where X, Y and Z are rows in, say, a table of projects). When a list entry is clicked, we branch to page P with the value of the list item placed in an application-level item (call it G_PROJECT). Reports on page P use G_PROJECT in their WHERE clauses.
    So, click list entry X and G_PROJECT is set to X and page P shows reports for project X.
    Page P also has a set of buttons which branch to various edit pages which allow attributes of page P's current project to be updated. These pages similarly use G_PROJECT in their WHERE clauses.
    Problem scenario:
    1. The user goes to page P and picks project X off the list. Project X's stuff is displayed (G_PROJECT = X).
    2. The user then picks project Y off the list. Project Y's stuff is displayed (G_PROJECT = Y).
    3. The user then clicks the browser's Back button. The page is served from browser cache, so project X's stuff is displayed, but G_PROJECT still = Y.
    4. The user clicks an 'Edit' button; we submit, and branch to an edit page which displays (and will edit) data for project Y because G_PROJECT still = Y.
    This is SERIOUSLY BAD NEWS - apart from being confusing, the user's edit permissions on projects X and Y may differ, and so the user may be able to perform 'illegal' updates.
    I've read what I can on this forum and the rest of the web looking for ways to a) inhibit browsers' 'Back' functions and/or b) prevent pages being cached by the browser, but none of them have worked for me.
    Short of waiting for browser manufacturers to recognise that the web is now full of applications as well as static pages, and enable robust programmatic control of cache behaviour, does anybody know how the problem can be avoided - or at least detected?
    Thanks,
    jd
    Failed attempts to date:
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="cache-control" content="no-store">
    <meta http-equiv="cache-control" content="private">
    <meta http-equiv="cache-control" content="max-age=0, must-revalidate">
    <meta http-equiv="expires" content="Wed, 09 Aug 2000 01:01:01 GMT">
    <meta http-equiv="pragma" content="no-cache">
    Disallowing duplicate submission (page attribute).
    window.history.go(1);

    Thanks Scott,
    I may be being dumb here but I don't see how that would help...
    P250_PROJECT and G_PROJECT are currently kept in sync by app logic. Whichever is used to drive, if the page is rendered from cache then the app logic is not executed, so the rendered page contents are not those keyed by P250_PROJECT, as illustrated in steps 1-4 of the problem above.
    The user sees X, the session items say Y. The engine doesn't know what the user is seeing.
    when page P is POSTed, its hidden item P250_PROJECT should always be used to derive the application item G_PROJECT. Then whether the page was pulled from cache or rendered anew via a click from the sidebar link, the project ID is determined by the contents of that page.
    As I said above I tried this, with the 'Edit' branch set to:
    Set these items: G_PROJECT
    With these values: &P250_PROJECT.
    but it makes no difference. The project ID is not determined by the rendered page contents - the engine gets the value of P250_PROJECT from session state.
    I can code the 'Edit' pages such that they check permissions and if necessary redirect back to p250 (conditional before-header branch), but that's a clunky cure rather than the prevention I was hoping for.
    Please tell me if my understanding is incorrect.
    jd

Maybe you are looking for

  • RFC to JDBC response

    Hello, I have a scenario SAP-> RFC -> XI -> JDBC. Where i'm using data from SAP R/3 to update a table in an Oracle database of a third party system. Is there any way i can find out if the fields have been updated succesfully or not? I know that only

  • Line break in sales order notes

    Hi, We use CRM 7.0. When the user tries to enter notes for a notes type Info in sales order, the entire notes come in one line or it uses its own way of breaking the line. The issue out here is , when the user wants to enter two lines, it is nort acc

  • How to call an htm page or internet explorer

    Hi, I have requirement to create help button in WEB UI and when clicking the help it should open my custom html page.. Currently i have the word document. Should i have to create a BSP application and if so how will i copy all the contents to the htm

  • Why are my images only showing as links on websites?

    Why are almost all of my images showing up as a link to the image. I put a code in right for embedded images but when i refresh or re-visit the page with the embedded image it is no longer embedded. It shows up as a link to the image which is quite a

  • Which RAW format of Digital camera does iPhoto '08 support?

    I couldn't find any document about that on the apple website. I've been using Panasonic DMC-FZ8 which is nice one but iPhoto 6 doesn't support yet. I'm going to buy iLife '08 if iPhoto '08 supports it. Anyone knows?