A question about synchronized Lists...

If I have a synchronized list, and I have a synchronized block in one thread with a lock on that list (synchronized(List)) am i supposed to be able to add an item to that list directly (using the List.add() method) from another thread while I'm still in the synchronized block previously described?
I have some code here where I tried to test that and the answer that I got is that it is possible while (I believe) it's not possible theoretically speaking.
import java.util.*;
public class Warehouse implements Runnable{
     List<String> items = Collections.synchronizedList(new ArrayList<String>());
//     List<String> items = new ArrayList<String>();
     public static void main(String[] args){
          Warehouse w = new Warehouse();
          Manager m = new Manager(w);
          Thread one = new Thread(w);
          Thread two = new Thread(m);
          one.start();
          two.start();
     public void add(String t){
          synchronized(items){               
               for(int i=0; i<2; ++i){
                    System.out.println("Warehouse added item...");
                    try{
                    Thread.sleep(500);
                    }catch(InterruptedException ie){
                         ie.printStackTrace();
               items.add(t);
               items.notify();
     public void run(){
          for(int i=0; i<1; ++i){
               synchronized(items){
                    while(items.isEmpty()){
                         try{
                         System.out.println("Warehouse waiting...");
                         items.wait();
//                         System.out.println("Warehouse after waiting...");
                         for(int j=0; j<2; ++j){
                              System.out.println("Warehouse after waiting...");
                              try{
                              Thread.sleep(500);
                              }catch(InterruptedException ie){
                                   ie.printStackTrace();
                         }catch(InterruptedException ie){
                              ie.printStackTrace();
class Manager implements Runnable{
     Warehouse w;
     public Manager(Warehouse w){
          this.w = w;
     public void run(){
          for(int i=0; i<1; ++i){               
               System.out.println("Manager Adding item...");
               w.add("articulo");                              
               for(int j=0; j<5; ++j){
                    w.items.add("jeje");
                    try{
                    Thread.sleep(500);
                    }catch(Exception ex){ex.printStackTrace();}
                    System.out.println("Manager adding to items");
               System.out.println("Manager finished with warehouse...");
}Output:
Warehouse waiting...
Manager Adding item...
Warehouse added item...
Warehouse added item...
*Warehouse after waiting...*
*Manager adding to items*
*Warehouse after waiting...*
*Manager adding to items*
Manager adding to items
Manager adding to items
Manager adding to items
Manager finished with warehouse...The code in "bold" (with the tokens) isn't supposed to happen concurrently as I understand it since the "warehouse after waiting" statement it's in the synchronized block with a lock on the items list and the "manager adding to items" statement is adding an item to that list through a direct reference to that list...

When the manager thread notifies the items (warehouse thread), the warehouse thread does not have to wake up automatically, it has to compete for the items lock then wait for its Thread context to execute. Which means that the manage is able to continue to execute - adding to items manually, and eventually sleep()ing. When the manager thread sleeps that is a good place for a Thread context switch, and if the JVM takes that opportunity to do so, then the warehouse thread regains the lock and would prevent further access to items. But at some point the Thread context will switch again (probably when warehouse thread goes to sleep). Now the manager thread can wake up, print that it is working because that code is not protected by any synchronized lock. Then when it attempts to add to items again it blocks. Another thread context switch allows the warehouse to complete its work, finish up, and release the items lock. Manager can then get the lock on items and finish its work. The results would be exactly as you display them. Here is a possible walk-through of the threading paths taken:
Thread == Warehouse
i = 0
  lock on items
    items.isEmpty == true
      print "Warehouse is waiting"
      items.wait (unlock items)
/* CONTEXT SWITCH */
Thread == Manager
i = 0
  print ""Manager Adding item..."
  locking items
    i = 0
      printing "Warehouse added item..."
      sleeping 500
    i = 1
      printing "Warehouse added item..."
      sleeping 500
    i ! < 2
    locking items
      adding to items
    unlocking items
    notifying items (wait will unlock eventually)
  unlocking items
  j = 0
    locking items
      adding to items
    unlocking items
    sleeping 500
/* CONTEXT SWITCH */
Thread == Warehouse
      items.wait (regain lock and get context)
      j = 0
        prinitng "Warehouse after waiting..."
        sleeping 500
/* CONTEXT SWITCH */
Thread == Manager
    sleeping 500 is done
    printing "Manager adding to items"
  j = 1
    locking items (blocking until items is available)
/* CONTEXT SWITCH */
Thread == Warehouse
        sleeping 500 is done
      j = 1
        printing "Warehouse after waiting..."
      j ! < 2
    itemse ! isEmpty
  unlocking items
i ! < 1
/* End of Warehouse Thread */
/* CONTEXT SWITCH */
Thread == Manager
    locking items (lock available)
      adding to itemes
    unlock items
    sleeping 500
    printing "Manager adding to items"
  j = 2
    locking items
      adding to itemes
    unlock items
    sleeping 500
    printing "Manager adding to items"
  j = 3
    locking items
      adding to itemes
    unlock items
    sleeping 500
    printing "Manager adding to items"
  j = 4
    locking items
      adding to itemes
    unlock items
    sleeping 500
    printing "Manager adding to items"
  j ! < 5
  printing "Manager finished with warehouse..."
i ! < 1
/* End of Manager Thread */So the theory an practice are the same - you can not access the items object when it is locked by another thread. The problem is that your test does not demonstrate when locks are held and released - some of the output you expect to be protected is not and so you mis-interpret the code.

Similar Messages

  • Question about "synchronized" and "wait"

    Hello, everyone!
    I have seen a piece of code like this,
    synchronized (lock)
    //do operation 1
    lock.wait();
    //do operation 2
    I think in the above piece of code, when a thead finished operation 1, it will release the lock and let other threads waiting for the lock have chance to run the same block of code. Am I correct?
    If I am correct, I have a further question, a "synchronized" block means a set of operations that can not be interrupted, but when invoke "wait" method, the thread running in the "synchronized" block will be terminated (interrupted) by release the lock and other threads will have chance to enter the "synchronized" block. In short, the execution inside the "synchronized" block will be interrupted. So, I wonder whether the above piece of code is correct and conforms to the principle of "synchronized". And what is its real use?
    Thanks in advance,
    George

    Thanks, pkwooster buddy!You're welcome
    I just wondered whether "wait inside a synchronized
    block" technology is thread safe. Please look at the
    following example,wait and synchronized are thread safe.
    public class Foo {
    int mVal= 0;
    public final Object mLock = ...;
    public void doIt() {
    synchronized(mLock) {
    mVal = ...;
    mLock.wait();
    if (mVal == ...) {
    // do something
    } else {
    // do something else
    }If we have two threads, T1 and T2, enter the block in
    their respective order, and T1 is woken up first, T2
    may have tampered with T1's execution path because T2
    changed mVal while T1 was asleep. So T2 manipulate
    instance field mVal is a side-effect.when you do the wait() you give up the lock and the other threads get a chance to run. When you exit the wait() you get the new value of the myVal variable which may have been changed. This is exactly what you want. To make that not thread save you could do
    int temp = myVal;
    wait();
    if(temp == ...)in this case the variable temp contains the old vale of myVal.
    >
    I think the most safest way is never wait inside a
    synchronized block, but it is less efficient. What do
    you think about the trick of wait inside a
    synchronized block? I think you are very experienced
    in thread field from your kind reply.
    Thanks in advance,
    Georgewait(), notify() and notifyAll() are very useful. You need them when you want threads to cooperate in an predictable manner. I recommend that you review the section on consumer and producer classes and wait and notify in the Threads Tutorial. It gives good examples. For a practical example of this you could also take a look at my Multithreaded Server Example. It implements a simple chat server that switches String messages. Look especially at the send(), doSend() and popMessage() methods in the StreamConnection class. These allow the receive thread of one user to send messages out using the send thread of another user. If you have questions about that example, please post the questions on that topic.
    Hope this helps.

  • Question about synchronized

    Hello everyone,
    Suppose I have a method which is a synchronized method (for example, method Foo in the following code block), and in this synchronized method another method which is not synchronized is invoked (for example, method Goo in the following code block). I am wondering when executing in Goo from Foo, whether we still have the synchronized feature (i.e. obtain the lock of "this" object).
    synchronized public Foo()
        Goo();
    private Goo()
    }Thanks in advance,
    George

    Kaj,
    Hi, pls see my post above - I replied to the same question in the other forum and I was pretty sure about my answer until I found it different from ur reply here.
    Here is my reply. Can u kindly guide me to what's wrong in it ?
    if a lock on a sync-ed method extends to all methods being called from it, then the jvm (bcos it has no means of knowing until runtime the method calls from a sync method) has to lock all the methods in a class that has atleast one sync method.
    What this would mean potentially is that the effect of sync-ing one method would be equal to sync-ing all the methods bcos any of the other methods could be potentially called from the sync-ed one.
    The example below is co-erced, but serves to illustrate the point.
         public class Test
        synchronized public  void Foo()
            Goo();
        synchronized public  void Moo()
            Goo();       
            notify();
        private void Goo()
            System.out.println(Thread.currentThread().getName()+" accessing goo");
            try
                if(Thread.currentThread().getName().equals("Th one"))
                     //force thread1 to wait , lets see if thread2 can access it while thread1's waiting on it
                    wait();
            catch(Exception e){}
            System.out.println(Thread.currentThread().getName()+" returning from goo");
    //first thread
    public class MyT implements Runnable
        Test t;
        public MyT(Test t)
            this.t = t;
        /* (non-Javadoc)
         * @see java.lang.Runnable#run()
        public void run()
            t.Foo();
    //second thread
    public class MyT2 implements Runnable
        Test t;
        public MyT2(Test t)
            this.t = t;
        /* (non-Javadoc)
         * @see java.lang.Runnable#run()
        public void run()
            t.Moo();
    //Main
    public class Main
        public static void main(String[] args)
            Test t = new Test();
            Thread th = new Thread(new MyT(t),"Th one");
            Thread th1 = new Thread(new MyT2(t), "Th two");
            th.start();
            th1.start();       
    And the o/p I got was
    Th one accessing goo/*thread one in goo, is in wait() coz of the funny if clause there*/
    Th two accessing goo /*there's no lock on goo, else with thread one in wait(), this wouldve been impossible*/
    Th two returning from goo/*Thread 2 is over with Goo(), will go back and notify Thread 1*/
    Th one returning from goo/*Thread 1 is notified, wakes up and returns :-)*/
    tx,
    ram.

  • Question about Linked Lists

    I'm doing an assignment on linked lists and I'm having trouble understanding the insert method. I'm using the one from the book and it works fine, but I don't quite understand it.
    public void insert(Object o) {
    Node n = new Node(o,current);
    if (previous == null)
    head = n;
    else
    previous.next = n;
    current = n;
    It's my understanding that current is the value that your currently at in the list. Previous is equal to the value before the current. So, previous.next is equal to current. This reasoning won't make the list progress with this code. Can someone tell me what I'm not understanding, or explain how this progresses?

    Thanks, that helps alot. Now, I have another question. I need to add and remove nodes from the list. I have it setup where the user can choose what node to delete. It compiles and runs fine, but when I try to delete a node, it doesn't delete it. Doing some troubleshooting, I found that it gets into the for loop, but doesn't do anything with the if/else statement. I put a printline in the if and else part, and it never printed out the statement in the if statement or in the else statement. Here's the code I'm using. getLentgh() is a method I wrote to return an integer value of how many nodes are in the list. I've also tried putting in a printline after the for loop, but still in the try, it didn't print it out.
    else if(source == remove) {
    String del = JOptionPane.showInputDialog("Enter an integer to remove.");
    Node temp = new Node(del,current);
    if(del != null){
    try{
         for(int c = 0; c < list.getLength(); c++){            
         if(temp.data == current.data){
              list.remove();
              c = list.getLength();
         else{
              list.advance();     
    }catch(NullPointerException e){
    }

  • Question about synchronized re-entry

    Suppose I have the following code:
    * method performs actions that require synchronization on state but
    * the programmer ensures manually that it is only called in a context
    * where we are already synchronized on state
    private void veryPrivateMethod() {
        //synchronized(state) { (*) required?
        if (state == 999) {
            // perform actions that require synchronization on state
    public void anotherMethod() {
        synchronized(state) {
            if (state == 42)
                state = 43;
            veryPrivateMethod();
    }See (*): If I ensure manually that veryPrivateMethod will only be called in a context where we are already synchronized on state, do I still need to specifically synchronize on state in the method (reentrant synchronization), or will it be better performance-wise and still safely synchronized if I omit the synchronized statement in veryPrivateMethod()?
    Thanks!

    gimbal2 wrote:
    932196 wrote:
    I synchronize on it whenever I change / compare-change it. Is this a bad ideaThat's a maybe. Its not a bad idea, as long as you realize that doing this has no special meaning and will offer no special protection. You can synchronize on just about any object you want, as long as other threads synchronize on the exact same object when wanting to execute the same section(s) of volatile code.the comment in the example is:
    // perform actions that require synchronization on statethis leads me to believe that the code is not correctly synchronized currently. like i said, changing the reference to the object you are synchronizing on pretty much always leads to broken code.

  • Questions about track listing and album

    I have burnt my collection of an audio drama I have on CD and transferred them to the Creative Vision M. The problem is the tracks play in alphabetical order, not in the numerical order (as in #1, 2, 3, etc.)
    I've gone and used MP3 Tag Editor to check the tracks 3 times. On my Archos, the tracks play according to order by #1(which happens to be the story order). How can I fix this order?
    Also, album isn't displayed despite the fact they've been attached using MP3 Tag Editor. The art is displayed on my Zune and the Archos but not on the Vision M.
    Help :robotsad:

    Eccentric_Hero wrote:
    In fact, now that I think about it... I didn't have to edit anything when I first uploaded them to the Archos.Message Edited by Eccentric_Hero on 04-29-2008 06:27 PM
    It could have something to do with the file system that was used... my old Zen MuVO played whatever I added in the order it was added because the file system was a external flash drive system. The Zune and the Zen both may use a different file system that plays and sort the tracks based on certain tag info. I know that from what I've read on here that the file system that the Zen uses is the main reason why SD card integration is impossible.
    Hope this helps,
    Frank.

  • Very simple question about webapp list layout.

    Hi Everyone!
    I am having a very simple issue. I have created a web app and it has a default list layout looks like:
    <table><tbody><tr><td>{tag_counter}. {tag_name}</td></tr></tbody></table>
    I have placed web app module (using {module_webapps,14273,a} ) in one of my page. In front-end it has show every thing fine except it shows table tag for each item:
    <table>
        <tbody>
            <tr>
                <td>1. <a href="/lot/lot-101">Castlepoint Lot 101</a></td>
            </tr>
        </tbody>
    </table>
    <table>
        <tbody>
            <tr>
                <td>2. <a href="/lot/efg-lot">EFG Lot</a></td>
            </tr>
        </tbody>
    </table>
    <table>
        <tbody>
            <tr>
                <td>3. <a href="/lot/some-lot">Some Lot</a></td>
            </tr>
        </tbody>
    </table>
    <table>
        <tbody>
            <tr>
                <td>4. <a href="/lot/some-other-lot">Some Other Lot</a></td>
            </tr>
        </tbody>
    </table>
    When I delete table and tbody tags from list view, it stop showing table related tags instead it start showing it without any tag.
    How to correct this issue? Please help!!!

    Here is what you can do:
    -edit the webapp list layout via FTP or via the "alpha" File Manager. The WYSIWYG editor will attempt to "correct" your HTML code. Enter something like this:
    <tr>
    <td>
    {tag_counter}. {tag_name}
    </td>
    </tr>
    -on the page you need the listing placed on enter this code:
    <table>
    <tbody>
    {webappmodule here}
    </tbody>
    </table>
    When the page renders you will get the desired result:
    <table>
    <tbody>
    <tr><td>1</td><td>Item1</td></tr>
    <tr><td>2</td><td>Item2</td></tr>
    <tr><td>3</td><td>Item3</td></tr>
    <tr><td>4</td><td>Item4</td></tr>
    </tbody>
    </table>

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

  • Quick Question about linked lists

    If I have a linked list can i save it to a file directly with the Serializable interface or would I have to iterate through each element and write each element to the file?

    yeah, it seems as though I can
    However, I am having a problem reading it back. I guess I don't know how to initialize the values in the list, as it doens't recognize anything until I add an item to it and it adds this item to the front, then any other items after that it will add to the back, when i want this first addition to be in the back as well.
    when I initialize the class i call
    list.add(loadList());
    loadList()
    public MyList loadList() {
               try {
                 FileInputStream fis = new FileInputStream("data.dat");
                 ObjectInputStream in = new ObjectInputStream(fis);
                 list = (MyList)in.readObject();
                 in.close();
                 return list;
               catch (Exception e) {
                   System.out.println(e);
              return list;
           }list.add()
    public void add(int index, Object o)
              if (index == 0) addFirst(o);
              else if (index >= size) addLast(o);
              else {
                   Node current = first;
                   for (int i = 1; i < index; i++)
                        current.prev = current;
                        current = current.next;
                   Node temp = current.next;
                   current.next = new Node(o);
                   current.prev = current;
                   (current.next).next = temp;
                   size++;
         }any ideas?

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

  • Quick question about a list

    I have a function in a component that has
    <function>
    <query queryOne>
    </query>
    <cfset to listOne>
    <query queryTwo>
    </query>
    <cfloop queryTwo>
    <cfif ListFind(listOne, queryTwo.field)>
    do this stuff
    </cfif>
    </cfloop>
    </function>
    I can see both queries pull the correct info when running
    them in my db program... but its not running my do this stuff...
    should I be able to access the list or do I have to so a
    variable.listOne? If it is right, them maybe I have some other
    logic issue, I just wanted to cross out one possible place I messed
    it up.
    Thanks,
    Va.

    Your sample code is a bit cryptic, but your problem is
    probably the ListFind function. If there is case sensitivity, use
    ListFindNoCase( ).

  • Question about synchronized singleton classes

    Hi,
    I have a singleton class, with only 1 method (which is static), I want access to that method to be synchronized, but someone suggested that I make my getInstance() method synchronized as well.
    Is this neccessary, or is it overkill?
    thanks!

    Example:
    static Instance getInstance() {
    if (instance == null) {
    instance = new Instance();
    return instance;
    }Two threads call it simultaneously:
    1. if (instance == null) { // evaluates true
    2. if (instance == null) { // evaluates true
    1. instance = new Instance(); // first instance
    2. instance = new Instance(); // second instance,
    deleting the reference to the first instance
    1. return instance; // which is not the originally
    created one but the second instance
    2. return instance;There's actually a worse consequence.
    1) T1 sees null
    2) T1 sets instance to point to where the object will live
    4) T2 sees non-null
    3) T2 returns, with a pointer to what's supposed to be an object, but isn't yet inited.
    4) T1 eventually inits the instance
    This can happen even if you use the "double check locking" pattern of synchronization.
    At least under the old memory model. I think the new JMM in effect in 5.0 (and possibly later 1.4) versions fixes it. I don't know if the fact that it can happen in absence of sync/DCL is an error or not, so I'm not sure if that's addressed in the new JMM, or if it's only the synced case that was a bug. (That is, it might be okay that it happens without syncing.)

  • Question about distribution lists

    I've create some distribution lists and added users to them.
    When I send a message directly to the user I can see it in the rcpt user mailbox.
    If I send a message to the distribution list to which the user subscribes, the unser doesn't receive the message in the mailbox
    I've to set something to see this messages?

    First verify that the user sending the email has permission to post to the list. Depending on how the list is set up, you may need to be a subscriber to send to the list, otherwise the message may be rejected.
    The next thing to check is the the mail queue to see if the message is stuck there. I do this by connecting to the es_mail database (using sqlplus) and running a query like this:
    select * from es_queue where queue = 5That will indicate if any messages are in the list queue (which is queue 5). If so, then it is possible that your list queue process is down. You can use the EM console to check the status of your list processes, or just run the oesctl command, eg:
    oesctl show targetsThis will return the list of mail processors configured on the local server. To get the status, just pick the list name and run:
    oesctl show status server-name:um_system:listThis should return something like:
    server-name:um_system:list:110291835244465386 ----Heartbeat-----

  • Question about Tasklists

    I have a weird question about task lists.
    lets assume I created a task list for a user and enering values in to a data form is one of the task and promoting the planning unit is the next step.
    and assume the user has gone through the tasks and completed entering the values and promoted and marked the tasks as complete.
    Now, I am the reviewer and review the values and promoted it back to him to change a few values where I am not satisfied.
    How does the user knows if he has to re-enter the values again? but the tasks in that tasklist shows the tasks has been completed.
    I am missing something or assuming it wrong. Can some one give me a clear picture idea about it. Appreciate your help.
    TIA
    sai

    Hi,
    Users get notification e-mails in which they would see annotation from previous plan unit owner if there is any. They could then know that they have to re-enter/adjust/amend some of the values. As for task lists, I usually recommend to users not to use complete box as it using it leads the same confusion you fell into. Task list completion status does not certainly serve to the purpose very well, so better stay away...
    What I can tell about workflow is that with good training and sensible security configuration, workflow works almost perfectly in many places.
    Cheers,
    Alp

  • Question about free down loading Mavericks. On checking Mavericks before downloading that there are no Bangla language in the list. I occasionally use Bangla in my present Mountain Lion. My concerns if I down load Mavericks then what will happen to Bangla

    Question about free downloading Mavericks. On checking Mavericks before downloading that there are no Bangla language in the list. I occasionally use Bangla in my present Mountain Lion. My concerns is, if I download Mavericks then what will happen to Bangla language in mountain lion? Samar Laha

    No reason to be embarassed. You are not alone.
    You will need an external drive. If you have a Time Machine drive without enough disk space you can create the clone there however it's advised that you keep your Time Machine and clone on separate drives. If the drive dies you loose both types of backup.
    Download and install the clone software. Everyone has their favorite. These are the two most common applications used. I prefer SuperDuper because of it's simplicity in setting up. It's also free for the first clone where with CCC you have to give a Credit Card then cancel if you do not want to keep.
    SuperDuper! http://www.shirt-pocket.com/
    CCC http://www.bombich.com/download.html
    Select your drive in the To popup. Click on Copy Now. That's it.
    Yes, it really is that simple....

Maybe you are looking for