Invoking notifyAll() on threads in a vector??

Each time I create a thread it gets added to a vector v. In the run method
of this thread I have a flag. If this flag for some reason is set to true
then that current thread will be set to wait:
run(){
          if (flag_wait){
              synchronized(this){
              try{
                  flag_wait = false;
                  wait();
              catch(InterruptedException e){}
}If I create two threads and sets their flag_wait to true, I will now in my
vector v have two threads that are waiting at index 0 and index 1.
Now I create a third thread that should only notify thread a index 1.
Therefore I would like to have another type of thread that has a reference
to this vector and this in its run method:
run(){
          if (flag_notify){
              synchronized(this){
              try{
                  flag_notify = false;
                  v.get(1).notifyAll(); // now only thread at index 1 should
be notified!
              catch(InterruptedException e){}
}But for some reason I cannot run notifyAll() on a thread in a vector!
Hope its possible to understand

I'm not sure you can do that (at least not the way you've described). notify() and notifyAll() does not provide a way for you to specify which thread will be notified. Assumimg your thrid thread has the object monitor, a call to notify() will notify a single thread (The choice is arbitrary and occurs at the discretion of the implementation.) A call to notifyAll() will notify all threads.
Also, you're doing thread.notifyAll(). But wait() is called on the current object. Per the API, the wait() method Causes current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object.
When you call wait, the current thread releases the monitor of the current object and waits in the pool of waiting threads for the current object. You need to call notify() or notifyAll() on the object within whose pool the thread is waiting.
What you have done is:
1. Force thread A to wait in the pool of the CURRENT OBJECT
2. Force thread B to wait in the pool of the CURRENT OBJECT
3. Call notify on thread A (this will notify all threads that are waiting in the pool of THREAD A). Though I suspect you are getting an IllegalMonitorException with that call since you may not have the monitor for thread A at that point.
Hope this helps.

Similar Messages

  • Thread Safety of Vector as Queue (Putting / Getting)

    i have a thread that is working on clearing a queue (a Vector).
    however, new items are being added to the queue intermittently.
    how should i do this properly?
    is the process below sufficient?
    Vectors are syncronized arent they?
    So using the methods below would it be safe if the Vector is
    having something removed as something is being added?
    public class QueueHandler extends Thread{
    public QueueHandler(){}
    public void run(){
    while(true){
    // if Queue.size() > 0 --> Handle Queue items
    // for(1 to size){ item = Queue.get(i); process(item)
    public void processItem(item){
    //do something
    // Queue.remove(item);
    public void addToQueue(item){
    Queue.add(item);
    Vector Queue;
    }

    import java.util.concurrent.*;
    public class QueueHandler extends Thread {
      public void run() {
        while(true) {
          processItem(queue.take());
      public void processItem(Object item) {
        //do something
      public void addToQueue(Object item) {
        queue.put(item);
      private BlockingQueue queue = new BlockingLinkedQueue();
    }

  • Hiding a JDialog invoked in a Thread.

    Hi,
    I have a Swing application that starts a Thread that in turn creates a modal JDialog. I need to use the Thread so that I can wait around for information entered in the Dialog while leaving the rest of the application interactive. However, when I do this, any attempt I try (hide and setVisible(false)) to remove the dialog visibly from the screen fails. I initialize the Dialog with null as the Parent frame. Is that my problem, or am I doing something else wrong?
    Thanks,
    Jason Mazzotta

    Generally you can close the dialog only from the event-dispatching thread. If you want to do it from another thread, you have to do the following:
    instead of calling
    setVisible( false );call
            SwingUtilities.invokeLater(
            new Runnable()
                public void run()
                     waitDlg.setVisible( false );

  • Why does it seem like notify() acts like notifyAll() for threads?

    I'm running a little exercise here:
    class Reader extends Thread {
          Calculator c;
           String name ="Fred";
           static int i = 0;
          public Reader(Calculator calc) {
             c = calc;
             name = "Fred"+(i++);
          public void run() {
             synchronized(c) {
               try {
                  System.out.println(name + " is waiting for calculation...");
                  c.wait();
               } catch (InterruptedException e) {}
               System.out.println("Total is: " + c.total + " for "+name);
         public static void main(String [] args) {
            Calculator calculator = new Calculator();
            new Reader(calculator).start();
            new Reader(calculator).start();
            new Reader(calculator).start();
            try {
                 Thread.sleep(1000);
              } catch (InterruptedException e) {
                   System.out.println("Got interrupted");
            calculator.start();
      class Calculator extends Thread {
         int total;
         public void run() {
            synchronized(this) {
               for(int i=0;i<100;i++) {
                  total += i;
               System.out.println("Notifying start");
               notify();
               System.out.println("Notifying end");
      }the output is
    Fred0 is waiting for calculation...
    Fred1 is waiting for calculation...
    Fred2 is waiting for calculation...
    Notifying start
    Notifying end
    Total is: 4950 for Fred0
    Total is: 4950 for Fred2
    Total is: 4950 for Fred1
    I expect only one "Total is: ..." output to come out since I expect only one thread to wake up from its waiting state from that notify() call. However all three threads wake up. What am I misunderstanding? I thought a thread waits forever unless you pass a time parameter into wait()... or am I wrong?
    Edited by: lapchern on Nov 17, 2009 12:53 PM

    Well, first of all, don't discard Exceptions and then wonder about the behaviour of a program :-).
    But that's not the issue here. From some quick testing, I didn't get the same behaviour when I ran using wait/notify on a lock object, not the thread itself:
    public class WaitNotify extends Thread {
          Calculator c;
         String name ="Fred";
         static int i = 0;
          public WaitNotify(Calculator calc) {
             c = calc;
             name = "Fred"+(i++);
          public void run() {
             synchronized(c.lock) {
               try {
                  System.out.println(name + " is waiting for calculation...");
                  c.lock.wait();
               } catch (InterruptedException e) {
                  e.printStackTrace();
               System.out.println("Total is: " + c.total + " for "+name);
         public static void main(String [] args) {
            Calculator calculator = new Calculator();
            new WaitNotify(calculator).start();
            new WaitNotify(calculator).start();
            new WaitNotify(calculator).start();
            try {
             Thread.sleep(1000);
          } catch (InterruptedException e) {
             System.out.println("Got interrupted");
            calculator.start();
      class Calculator extends Thread {
         int total;
         final Object lock = new Object();
         public void run() {
            synchronized(lock) {
               for(int i=0;i<100;i++) {
                  total += i;
               System.out.println("Notifying start");
               lock.notify();
               System.out.println("Notifying end");
      }Not sure ATM why that is, but it's I think best practice not to lock on the Thread itself and instead a different Object, so there's a fix. It'll give you a place to start investigating.
    Edit: Might be good to look at the [Javadoc for Object.wait()|http://java.sun.com/javase/6/docs/api/java/lang/Object.html#wait()]:
    ...interrupts and spurious wakeups are possible, and this method should always be used in a loop:
         synchronized (obj) {
    while (<condition does not hold>)
    obj.wait();
    ... // Perform action appropriate to condition
    Edited by: endasil on 17-Nov-2009 4:08 PM
    Edited by: endasil on 17-Nov-2009 4:09 PM

  • Invoking "this.notify()" before thread exit?

    a Runnable class that i am writing must account for 2 cases:
    (1) the user wants to do other work while the Runnable does its business.
    (2) the user wants to wait for the Runnable to exit before continuing on with other work.
    this is my best solution:
    MyRunnable mr = new MyRunnable();
    new Thread(mr).start();
    synchronized(mr) {
      mr.wait();
    public class MyRunnable implements Runnable {
      public void run() {
        synchronized(this) {
          this.notifyAll(); // just before exit, i notify everyone that i am exiting. but if no one is waiting, what harm does this do?
    } further, why not do this.notifyAll() for all Threads / Runnables just before they exit?
    if no one is waiting, is there harm in invoking notifyAll() ? seems that this just adds a new feature to my class at no cost??
    my understanding of OOP is that a class writer should not assume how a user will use his class, so this seems like a good option. yet, this does seem non-standard.
    Edited by: kogose on Oct 19, 2008 11:53 AM

    But why start a thread at all only to wait for it? In the case where the caller wants to wait, he should just call your run() method directly. No other code required. In the case where he wants to proceed independently, he can call new Thread(xxx).start().

  • Vector Replacement in Java 1.4 - Is Thread Safety Needed In This Scenario?

    I have a Java 1.4 application that queries Database # 1, and builds custom strings used to create records that are inserted into Database # 2.
    Right now Vectors are used as a container to temporarily hold query output from Database # 1 while building records going into Database # 2, but I want to convert away from this legacy collection type.
    This application does this with a single "worker" thread that is started and monitored by the application main thread. If the main thread detects any exceptions, i.e. a network or any database problem, the application main thread will stop the single worker thread and restart a new single worker thread.
    There are several instances of this application running simultaneously on the same server but accessing different test databases. When put into the production environment this application will run on a separate server and there will be only 1 instance of the application running.
    I have reviewed numerous forums here and Google results and have not found much specific info that would closely apply to my exact design situation. I did not post any code since this is more of a design question than issue with a specific code snippet.
    My question is: In the scenario I described, does thread safety need to be a factor in choosing a new collection type (to replace Vectors) and in building code that accesses this new collection type?

    The several instances of the application are all independent JVMs and can't interact with each other directly at all. So there's no thread safety issue there and there never was. So what does that leave you? You've got a single worker thread using the Vector? There's no thread safety issue there either. The only time you have to think about thread safety is when two threads are trying to use the same object.

  • Wake up a specific thread

    Hello All,
    We have a site that has the potential of multiple users hitting our site at the same time. Each user initiates a transaction request, which goes to a controller servlet and then fires off a transaction worker. While these transaction are running, the request enters a synchronized method (a java thread monitor) that puts the request into a pool until the transaction worker completes.
    My question is: how do you ensure that you only wake up the specific request that fired off the transaction worker, when the transaction worker is completed?
    Any help is appreciated,
    Thanks!
    James

    Have the worker invoke notifyAll() on the request object and the caller (your servlet) invoke wait() on the same object. Since one and only one client thread will exist for each request, that will work fine. Use the pool (queue?) to hold requests that have not yet been taken by a worker. The workers .wait() on the queue (or some other monitor) for work to do.
    Consider using Doug Lea's excellent Executor class from his concurrency library (http://gee.cs.oswego.edu/dl/classes/EDU/oswego/cs/dl/util/concurrent/intro.html), it and the associated classes handles these kinds of need beautifully. Oh and they are also the basis of the work in JSR 166 to create a set of standardized concurrency utility classes in a future version of Java...
    Chuck

  • Are static nested classes thread-safe?

    There doesn't seem to be any definitive answer to this. Given the following code, is it thread-safe?
    public class SomeMultiThreadedWebController {
    public HttpServletResponse someMethodToExecuteViaWebRequest(HttpServletRequest request) {
        simpleQueryBuilder("SELECT...").addParameter("asdf","asdf").createQuery(EMF.getEntityManager()).executeUpdate();
    protected static class SimpleQueryBuilder {
             private String queryString;
             private Map<String, Object> params = new HashMap<String, Object>();
             public SimpleQueryBuilder(String queryString) {
                  this.queryString = queryString;
             public SimpleQueryBuilder addParameter(String name, Object value) {
                  params.put(name, value);
                  return this;
             public Query createQuery(EntityManager em) {
                  Query query = em.createQuery(queryString);
                  for (Entry<String, Object> entry : params.entrySet()) {
                       query.setParameter(entry.getKey(), entry.getValue());
                  return query;
        public static SimpleQueryBuilder simpleQueryBuilder(String queryString) {
             return new SimpleQueryBuilder(queryString);
    }Forget whether or not someone would do this, as this is just an example. I'm really trying to get at whether or not the instance variables inside the static nested class are thread-safe. Thanks for any responses.

    Hello,
    I believe you understand what you're talking about, but you state it in a way that is very confusing for others.
    Let me correct this (essentially, incorrect uses of the terminology):
    I agree that thread-safe or not is for an operation, for a member, it has some sort of contextual confusion.
    Member has a much broader meaning in the [Java Language Specification|http://java.sun.com/docs/books/jls/third_edition/html/names.html#6.4] . Even "class member" applies to both an attribute, a method, or an inner class or interface.
    I think you mean "member variable" of a class (aka "attribute" or "field"). By the way, static or not is irrelevant to the rest of the discussion.
    For an operation or a member, if there's only one thread could access it atomically in one moment, we could call it thread-safe.Mmm. I was tempted to say yes (I'm reluctant to commit myself). With an emphasis on "_The encapsulating class_ makes this member's usage thread-safe".
    Still, just synchronizing each operation on a member is not enough to make all usages "thread-safe":
    Consider a java.util.Vector: each add/get is synchronized, so it is atomic, fine.
    However if one thread adds several values, let's say 3, one by one, to a vector that initially contains 0 values, and another thread reads the vector's size() (another properly synchronized method), the reader thread may witness a size anywhere among 0, 1, 2, 3, which, depending on the business logic, may be a severely inconsistent state.
    The client code would have to make extra work (e.g. synchronizing on the vector's reference before the 3 adds) to guarantee that the usage is thread-safe.
    Thus any synchronized method(With the limit stated above)
    or immutable member (like primitive type) are thread-safe.
    Additionally for a member, if it's immutable, then it's thread-safe. You mean, immutable primitive type, or immutable object. As stated previously, an immutable reference to a mutable object isn't thread-safe.
    a static final HashMap still have thread-safe issue in practice because it's not a primitive.The underlined part is incorrect. A primitive may have thread-safety issues (unless it's immutable), and an object may not have such issues, depending on a number of factors.
    The put, get methods, which will be invoked probably, are not thread-safe although the reference to map is.Yes. And even if the put/get methods were synchronized, the client code could see consistency issues in a concurrent scenario, as demonstrated above.
    Additional considerations:
    1) read/write of primitive types are not necessarily atomic: section [ §17.7 of the JLS|http://java.sun.com/docs/books/jls/third_edition/html/memory.html#17.7] explicitly states that writing a long or double value (2 32-bits words) may not be atomic, and may be subject to consistency issues in a concurrent scenario.
    2) The Java Memory Model explicitly allows non-synchronized operations on non-volatile fields to be implemented in a "thread-unsafe" way by the JVM. Leading way to a lot of unintuitive problems such as the "Double-Checked Locking idiom is broken". Don't make clever guess on code execution path unless you properly synchronize access to variables across threads.
    Edited by: jduprez on Mar 4, 2010 9:53 AM

  • Thread Contention

    I've written a producer/consumer type of application. the producer receives data input (speed and time) over a serial connection and places it in a queue of sorts, set up much like the examples at Sun. The consumer picks up the values, calculates a speed and moves an animation object across a display.
    I've put both the consumer and producer programs in their own threads. the driver program starts the producer program in its thread and calls an openConnection method to open a serial connection. I then call a startCollecting method that begins reading serial input. The input is dumped in the queue, which has a capacity of 5 values. If the producer fills all five values, it goes into a wait state. the consumer is supposed to pick up the values, freeing the producer to place more values in the queue. My problem is once the producer goes into its wait state, everything freezes, including the driver program interface, and the visual display the consumer is running in.
    If I do not call the openConnection and startCollecting separately, but rather just start the producer thread and let it open a connection and start collecting automatically all runs well. It seems the problem exist whenever I attempt to access methods inside the threaded program.
    Any help would be greatly appreciated. Have not found any really examples of how to resolve this approach.

    I've put both the consumer and producer programs in
    their own threads.good.
    the driver program starts the
    producer program in its thread and calls an
    openConnection method to open a serial connection. I
    then call a startCollecting method that begins reading
    serial input. The input is dumped in the queue, which
    has a capacity of 5 values. If the producer fills all
    five values, it goes into a wait state. the consumer
    is supposed to pick up the values, freeing the
    producer to place more values in the queue. My problem
    is once the producer goes into its wait state,
    everything freezes, including the driver program
    interface, and the visual display the consumer is
    running in. this sounds like you possibly missed something in the area of thread synchronization. did you invoke notifyAll() after you put somthing in the queue?
    the typical queue implementation looks like this:
    package farmerworker;
    import java.util.*;
    * A thread safe queue used to synchronize farmers and workers. Farmers put
    * objects into the queue and workers retrieve them. Workers may arbitrarily
    * invoke {@link #dequeue()}. Their thread blocks until an instance can be
    * retrieved from the queue or the thread is interrupted. <p>
    * technically {@link #enqueue( Object )} and {@link #dequeue()} are
    * synchronized using {@link #wait()} and {@ #notify()}.
    * @author    klemme
    * @created   24. September 2001
    * @version   $Revision$
    public class Queue {
         * Checks whether there are objects in the queue.
         * @return   'true' if there are instances in the queue. WARNING: in a
         *      multithreaded environment it is only reasonable to invoke this
         *      method when holding a lock on this instance, i.e. in a <code>synchronized</code>
         *      block.
        public boolean isEmpty() {
            synchronized ( lock ) {
                return queue.isEmpty();
         * Return the number of objects currently in the queue.
         * @return   a value >= 0
        public int size() {
            synchronized ( lock ) {
                return queue.size();
         * Put an object into the queue.
         * @param obj  the instance to enque
        public void enqueue( Object obj ) {
            synchronized ( lock ) {
                queue.add( obj );
                lock.notify();
         * Retrieve something from the queue. This method blocks until either an
         * Object can be retrieved from the queue or this thread is interrupted.
         * @return                          the next Object in the queue
         * @exception InterruptedException  in case of premature termination of this
         *      thread.
        public Object dequeue()
            throws InterruptedException {
            synchronized ( lock ) {
                while ( isEmpty() ) {
                    lock.wait();
                return queue.remove( 0 );
        private List queue = new LinkedList();
         * The lock on which this instance synchronizes.
        protected final Object lock = queue;
    [/code}]instead of synchronizing on "lock" you can just synchronize methods.  then you have to invoke notifyAll() and wait() on "this".  you can also change the conditions when the queue accepts new input.  this Queue is unbounded, but you can implement a size limit via a condition testing for the size in enqueue(). (typically this is easier done then working with a ring buffer in a fixed sized array, since then you need two indexes etc. and the overhead of a LinkedList is not too big. - btw: LinkedList is faster than ArrayList if you don't need indexed access like in this case.)
    regards
    robert

  • Thread resume

    cant resume the thread after thread wait is called
    plz help
    import javax.swing.*;
    import java.awt.*;
    import java.util.*;
    public class numbers {
         filee p=new filee();
         Thread t=new Thread(new sclass());
         public static void main(String []args){
              numbers n=new numbers();
              n.all();
              n.resume();
            public void all(){
                  t.start();
            public void resume(){
                 String input=JOptionPane.showInputDialog(null, "Enter 1 to resume");
                if(input.equals("1")){
                      p.resume();
    class sclass implements Runnable{
         filee f=new filee();
         public void run(){
              f.printnum();
    class filee{
         int i;
         public synchronized void printnum(){
              for(i=0;i<100;i++){
                   System.out.print(i);
                   if(i==50){
                        try{
                        Thread.sleep(4000);
                        }catch(Exception e){
                   if(i==60){
                        try{
                             wait();
                        }catch(Exception e){
                             System.out.println(e);
         public synchronized void resume(){
              notifyAll();
    }

    The wait()-method doesn't work like that.
    Read the tutorial, or maybe the full tutorials about that.
    Edit: I now see you're not invoking the (deprecated) resume-method on Thread, but on a Filee-object. The problem is that you have to invoke notifyAll() on the SAME object as you invoked wait() on, and you obviously don't do that.
    Edited by: Peter_vd_Wal on 30-mei-2009 11:21

  • Urgent : UI refresh problem on dual processor or hyper threaded machine

    Hello,
    I am developing an applet that displays a set of tabs to the user. Each tab contains JLists.
    When user selects from any of the JList(s), all lists are updated to reflect what is still available for selection. Number of elements in the list can be as large as few hundred thousands. This all works fine on single processor machine.
    However, when running same on dual processor or Intel hyperthreaded processor, lists are not updated correctly. What I meant is that, for example, if a list originally has 100 thousands elements in it, then when I select an element from it, list is updated with available elements.Assume there are only 2 thousand elements available after above selection.Everything is fine so far, but when I de-select my selection, list is suppose to be updated again with original 100 thousands elements displayed again. The real problem is list indeed gets updated properly but few elements from list are not visible on the screen. However, If I minimize the browser(as it is an applet) and restore it again, all elemnets within the list are displayed correctly. Any help will be highly appreciated.

    When your JLIst refresh occurs, the items are loaded into the JList from some other Object right? Nt knowing more about your code, I can't say exactly what that would be.Yes, you are right. Let me explain in breif about the architecture of the code.
    I have a class,say CatPanel, that extends from JPanel and has BorderLayout with JList (wrapped in JScrollPane) in the center.
    The main GUI class controls all such CatPanels.So, when the list is to be updated, GUI class invokes a method from CatPanel with Vector of elements to be inserted as an argument. Elements are inserted using setListData method of the JList.
    If I'm right, the this might explain the behavior you are seeing. In a single processor environment, the data >is not cahced and therefore everything is fine. When you go to the dual-processor machine, the threads >have their own caches and are not always in sync. When you mimize the window and restoer it, this could >trigger a resync of the cache.Is there a way to trigger such synchronization?
    One thing I'm not sure about is, when you return to the 'main' list, do you still see the selected sublist or >the main list with some elements missing? When a list is updated as a result of de-selection, few elements from start of the list are not visible.
    I can see all other elements by using ScrollBar. So, if there are some selections that belong to the begining portion of the list, then selected sublist is not visible.
    Let me explain with following example. Assume that with current selection, I have 100 elements in the list and all of them are visible on the screen. Now as a result of de-selection, suppose now the list should contain 200 elements rather than 100 elements. So, what happens in this case is that if first 50 elements are not visible in the list then I can see blank space corresponding to first 50 elements at the start of the list followed by remaining elements. I tried overloading paint method of an element that is actually inserted into the list, but still the result is same.

  • Java API - EventHandler threads not getting killed

    Hello everybody,
    I didn't know whether to post this in the PI forum or in the MDM forum. I use the following scenario:
    We run an EJB session bean in the Java Proxy environment of PI 7.1. In this bean we create an MDM session, log on to a repository and then attach a RecordListener that reacts to any change of the records. When an interesting change took place, the record is distributed to PI.
    The code looks like this:
    EventDispatcher evDis = new EventDispatcher(servername);
    RecordListener recLis = new RecordListener();
    evDis.registerDataNotifications(username, password, repIdent, regions[0]);
    evDis.addListener(recLis);
    The problem arises when we try to undeploy or stop the application. You would assume that it would stop everything connected to the application. However, it does not. The mentioned EventDispatcher creates a thread object when invoked, and this thread is never killed. The consequence: Records keep getting distributed as if nothing had happened, although the application is gone (even undeploying doesn't help). But when we redeploy the application, a new thread is created. So after some development you get 10 or more threads firing every change to PI. The only thing that helps is a restart of the J2EE engine.
    So, my question: Has anybody here made a similar experience? Is this common for MDM or is rather PI the cause of this issue?
    Any comments on that are very welcome.
    Best regards,
    Jörg

    Hi Veera,
    thanks a lot, that pot me on the right track! In fact, it's the @PreDestroy annotation which has to be used for some cleanup method. When we execute this and included the coding you mentioned the threads are killed properly.
    Currently we're facing the issue that somehow the commit status of the bean is not set to "Committed" and from the second message on we get exceptions. If anybody came across this, help is appreciated.
    Best regards,
    Jörg

  • One thread adding/updating value  and other thread getting values....issue

    am using a spring bean (singleton) and this is how it looks like
    public class MySingletonService {
    private Map<String, List<TaskVO>> alerts = new HashMap<String, List<TaskVO>>();
    //spring will call this method every 15 minutes
    public void pollDatabase() {
    //initialize the alerts instance variable and create/fill the alerts instance variable with new alerts for the employee(from database) .The key for the hashmap is the employee id
    //some client code (e.g. GUI) will call this method to get the alert for the operator id.This can be called anytime to get the latest info from the alert Map
    public List<TaskAlertVO> getOutstandingAlerts(String operatorId) {
    return alerts.get(operatorId);
    The issue here is that when getOutstandingAlerts is invoked by a thread,some other thread(Spring) calling the pollDatabase method might be updating the value.Please give me some idea and solution to get around this issue.
    I was thinking of creating a copy of alerts instance variable in the getOutstandingAlerts method and then use the copy to find the key and return the alert for that operator id.This way we dont have to worry about data conflict.
    Please advice

    Manjit wrote:
    jtahlborn wrote:
    if the pollDatabase() method is getting a complete new copy of the alerts every time, and the alerts map isn't being modified at all after load, then you can just:
    - make the alerts member variable volatible
    - create a new HashMap each time pollDatabase() is called, fill it in, and then assign it to the alerts member variable. Jtalhorn,I think I got your point.Basically you are suggesting that by creating a brand new map in each pollDatabase operation, then I dont have to worry about get operation ,simply because the client code is still looking at old memory location(old copy) and hence should not worry about values getting changes by pollDatabase method.
    I got it.
    But the small doubt is that why even I should bother about making the instance variable volatile ? Your suggestion should work without making it volatilebecause volatile ensures correct memory visibility between threads. if you didn't use volatile, then a caller to getOutstandingAlerts() could see some partially initialized/corrupt version of the map.

  • Java synchronization mechanism allows two threads to hold the same lock?

    Dear all,
    I am a little bit puzzled since I cannot explain why I get the following behavior.
    I have a small Java program to draw components. The drawings are cached in the memory for performance improvements. The cache is access by two different threads. Now the funny thing: even I synchronized every access to the cache, I still get ConcurrentModificationExceptions.
    Here is a part of the code:
         @Override public void paint(Graphics g2) {
              // Check if the image is in the cache
              Image drawing;
              synchronized (m_Cache) { drawing = m_Cache.get(m_CurrentOffset); }
              if (drawing == null) {
                   // The image is not cached, so draw it
                   // Put the image into the cache
                   synchronized (m_Cache) { m_Cache.put(m_CurrentOffset, drawing); }
         public void componentResized(ComponentEvent e) {
              // Upon resizing of the component, adjust several pre-calculated values
              // And flush the cache
              synchronized (m_Cache) { m_Cache.clear(); }
         public void elementUpdated(IHexGridElement Element) {
              // Clear cache where the element may be contained at
              synchronized (m_Cache) { for (Point p : m_Cache.keySet()) { if (isElementInScope(Element.getIndex(), p, new Point(p.x + m_MaxColumn, p.y + m_MaxRow))) { m_Cache.remove(p); } } }
         }The paint and componentResized methods are invoked by the AWTEventQueue-0 thread. The elementUpdated method is invoked by "MyThread" thread.
    Now my question is why do I get java.util.ConcurrentModificationException, especially in situations where a lot of repaintings have to be done and the window is resized? When I remove the caching stuff, everything works perfect, but only a little bit slow.
    Thanks for any help.

    In your elementUpdated method, you are using an Iterator to walk over the set of keys in your map. You can't see the Iterator, because you are using the new for-each loop syntax which hides it from you - but it's there under the covers. You are then removing elements from your map directly. This is what causes your ConcurrentModificationException.
    You should re-write your loop to explicitly use an iterator, and then do your remove operation through the iterator.
    Incidentally, you have a slight race condition in your paint method. Two (or more) threads could simultaneously discover that a given image is not cached, then both draw it, then both cache it. If the drawing operation produces the same drawing every time, then the only problem this causes is the overhead of drawing the image multiple times. To fix this, wrap the get, draw and put operations in a single synchronized block.

  • Problem when invoking a web service multiple times

    Hello,
    I have a java client which invokes an apache axis web service (deployed on an Oracle Application Server on a remote machine) multiple times.
    The client distributes the web service invokes among multiple threads, every thing goes well but after an average of 300 web service invokes (among all threads) ab exception is thrown from the client:
    java.net.SocketException: Unable to establish connection
    at org.apache.axis.AxisFault.makeFault(AxisFault.java:101)
    at org.apache.axis.transport.http.HTTPSender.invoke(HTTPSender.java:154)
    at org.apache.axis.strategies.InvocationStrategy.visit(InvocationStrategy.java:32)
    at org.apache.axis.SimpleChain.doVisiting(SimpleChain.java:11
    at org.apache.axis.SimpleChain.invoke(SimpleChain.java:83)
    at org.apache.axis.client.AxisClient.invoke(AxisClient.java:165)
    at org.apache.axis.client.Call.invokeEngine(Call.java:2784)
    at org.apache.axis.client.Call.invoke(Call.java:2767)
    at org.apache.axis.client.Call.invoke(Call.java:2443)
    at org.apache.axis.client.Call.invoke(Call.java:2366)
    at org.apache.axis.client.Call.invoke(Call.java:1812)
    at standardwebservice.StandardWebserviceSoapBindingStub.getStandardWebserviceData(StandardWebserviceSoapBindingStub.java:225)
    at standardwebservice.StandardWebserviceProxy.getStandardWebserviceData(StandardWebserviceProxy.java:50)
    at main.VericalThread.run(VericalThread.java:65)
    Caused by: java.net.SocketException: Unable to establish connection
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.PlainSocketImpl.doConnect(Unknown Source)
    at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
    at java.net.PlainSocketImpl.connect(Unknown Source)
    at java.net.SocksSocketImpl.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at sun.reflect.GeneratedMethodAccessor8.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.apache.axis.components.net.DefaultSocketFactory.create(DefaultSocketFactory.java:153)
    at org.apache.axis.components.net.DefaultSocketFactory.create(DefaultSocketFactory.java:120)
    at org.apache.axis.transport.http.HTTPSender.getSocket(HTTPSender.java:191)
    at org.apache.axis.transport.http.HTTPSender.writeToSocket(HTTPSender.java:404)
    at org.apache.axis.transport.http.HTTPSender.invoke(HTTPSender.java:13
    ... 12 more
    Thread No. 1 Start for calling 1210ZD106MAT2AAxisFault
    faultCode: {http://schemas.xmlsoap.org/soap/envelope/}Server.userException
    faultSubcode:
    faultString: java.net.SocketException: Unable to establish connection
    faultActor:
    faultNode:
    faultDetail:
    {http://xml.apache.org/axis/}stackTrace:java.net.SocketException: Unable to establish connection
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.PlainSocketImpl.doConnect(Unknown Source)
    at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
    at java.net.PlainSocketImpl.connect(Unknown Source)
    at java.net.SocksSocketImpl.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at sun.reflect.GeneratedMethodAccessor8.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.apache.axis.components.net.DefaultSocketFactory.create(DefaultSocketFactory.java:153)
    at org.apache.axis.components.net.DefaultSocketFactory.create(DefaultSocketFactory.java:120)
    at org.apache.axis.transport.http.HTTPSender.getSocket(HTTPSender.java:191)
    at org.apache.axis.transport.http.HTTPSender.writeToSocket(HTTPSender.java:404)
    at org.apache.axis.transport.http.HTTPSender.invoke(HTTPSender.java:13
    at org.apache.axis.strategies.InvocationStrategy.visit(InvocationStrategy.java:32)
    at org.apache.axis.SimpleChain.doVisiting(SimpleChain.java:11
    at org.apache.axis.SimpleChain.invoke(SimpleChain.java:83)
    at org.apache.axis.client.AxisClient.invoke(AxisClient.java:165)
    at org.apache.axis.client.Call.invokeEngine(Call.java:2784)
    at org.apache.axis.client.Call.invoke(Call.java:2767)
    at org.apache.axis.client.Call.invoke(Call.java:2443)
    at org.apache.axis.client.Call.invoke(Call.java:2366)
    at org.apache.axis.client.Call.invoke(Call.java:1812)
    at standardwebservice.StandardWebserviceSoapBindingStub.getStandardWebserviceData(StandardWebserviceSoapBindingStub.java:225)
    at standardwebservice.StandardWebserviceProxy.getStandardWebserviceData(StandardWebserviceProxy.java:50)
    at main.VericalThread.run(VericalThread.java:65)
    By the way, when I deploy the same web service on an oracle application server on a local machine (in same physical network), every thing goes well and this exception doesn't appear.
    By the way, I also tried a JAX-RPC web service and the same exception is thrown.
    So please can somebody give me a help.

    Hello,
    I have a java client which invokes an apache axis web service (deployed on an Oracle Application Server on a remote machine) multiple times.
    The client distributes the web service invokes among multiple threads, every thing goes well but after an average of 300 web service invokes (among all threads) ab exception is thrown from the client:
    java.net.SocketException: Unable to establish connection
    at org.apache.axis.AxisFault.makeFault(AxisFault.java:101)
    at org.apache.axis.transport.http.HTTPSender.invoke(HTTPSender.java:154)
    at org.apache.axis.strategies.InvocationStrategy.visit(InvocationStrategy.java:32)
    at org.apache.axis.SimpleChain.doVisiting(SimpleChain.java:11
    at org.apache.axis.SimpleChain.invoke(SimpleChain.java:83)
    at org.apache.axis.client.AxisClient.invoke(AxisClient.java:165)
    at org.apache.axis.client.Call.invokeEngine(Call.java:2784)
    at org.apache.axis.client.Call.invoke(Call.java:2767)
    at org.apache.axis.client.Call.invoke(Call.java:2443)
    at org.apache.axis.client.Call.invoke(Call.java:2366)
    at org.apache.axis.client.Call.invoke(Call.java:1812)
    at standardwebservice.StandardWebserviceSoapBindingStub.getStandardWebserviceData(StandardWebserviceSoapBindingStub.java:225)
    at standardwebservice.StandardWebserviceProxy.getStandardWebserviceData(StandardWebserviceProxy.java:50)
    at main.VericalThread.run(VericalThread.java:65)
    Caused by: java.net.SocketException: Unable to establish connection
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.PlainSocketImpl.doConnect(Unknown Source)
    at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
    at java.net.PlainSocketImpl.connect(Unknown Source)
    at java.net.SocksSocketImpl.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at sun.reflect.GeneratedMethodAccessor8.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.apache.axis.components.net.DefaultSocketFactory.create(DefaultSocketFactory.java:153)
    at org.apache.axis.components.net.DefaultSocketFactory.create(DefaultSocketFactory.java:120)
    at org.apache.axis.transport.http.HTTPSender.getSocket(HTTPSender.java:191)
    at org.apache.axis.transport.http.HTTPSender.writeToSocket(HTTPSender.java:404)
    at org.apache.axis.transport.http.HTTPSender.invoke(HTTPSender.java:13
    ... 12 more
    Thread No. 1 Start for calling 1210ZD106MAT2AAxisFault
    faultCode: {http://schemas.xmlsoap.org/soap/envelope/}Server.userException
    faultSubcode:
    faultString: java.net.SocketException: Unable to establish connection
    faultActor:
    faultNode:
    faultDetail:
    {http://xml.apache.org/axis/}stackTrace:java.net.SocketException: Unable to establish connection
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.PlainSocketImpl.doConnect(Unknown Source)
    at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
    at java.net.PlainSocketImpl.connect(Unknown Source)
    at java.net.SocksSocketImpl.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at sun.reflect.GeneratedMethodAccessor8.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.apache.axis.components.net.DefaultSocketFactory.create(DefaultSocketFactory.java:153)
    at org.apache.axis.components.net.DefaultSocketFactory.create(DefaultSocketFactory.java:120)
    at org.apache.axis.transport.http.HTTPSender.getSocket(HTTPSender.java:191)
    at org.apache.axis.transport.http.HTTPSender.writeToSocket(HTTPSender.java:404)
    at org.apache.axis.transport.http.HTTPSender.invoke(HTTPSender.java:13
    at org.apache.axis.strategies.InvocationStrategy.visit(InvocationStrategy.java:32)
    at org.apache.axis.SimpleChain.doVisiting(SimpleChain.java:11
    at org.apache.axis.SimpleChain.invoke(SimpleChain.java:83)
    at org.apache.axis.client.AxisClient.invoke(AxisClient.java:165)
    at org.apache.axis.client.Call.invokeEngine(Call.java:2784)
    at org.apache.axis.client.Call.invoke(Call.java:2767)
    at org.apache.axis.client.Call.invoke(Call.java:2443)
    at org.apache.axis.client.Call.invoke(Call.java:2366)
    at org.apache.axis.client.Call.invoke(Call.java:1812)
    at standardwebservice.StandardWebserviceSoapBindingStub.getStandardWebserviceData(StandardWebserviceSoapBindingStub.java:225)
    at standardwebservice.StandardWebserviceProxy.getStandardWebserviceData(StandardWebserviceProxy.java:50)
    at main.VericalThread.run(VericalThread.java:65)
    By the way, when I deploy the same web service on an oracle application server on a local machine (in same physical network), every thing goes well and this exception doesn't appear.
    By the way, I also tried a JAX-RPC web service and the same exception is thrown.
    So please can somebody give me a help.

Maybe you are looking for