Notify/Wait or Observable/Observer?

Hi,
I have one thread process the data and store the result in a data object. Several threads access the data object to display.
Which one to use:
1) Have the processing thread notify the display threads when it's done? Using thread wait()/notify()?
2) Have the data object be the observable, and the dislay threads be the observers? Using the observable/observer concept?
Thanks

How exactly would you code the wait/notify method calls? I had dynamic data that was used to update the data models for a JList and a JTable, and found it difficult to notify the models correctly, after the data changed.
Somehow the object has to "post" the fact that it has changed, a job for Observer/Observable. The Thread tutorial and the various Swing tutorials don't quite describe this in a way I understand. Can somebody give an example of how to use notify/wait in this sort of situation? Thanks.

Similar Messages

  • CDI event originator's EJB transaction waits for Observer(AFTER_SUCCESS) EJ

    Hi!
    I have the following scenario: (pesudo-code)
    CallerObject.method() {
    SessionBean1.method1(); // through remote bean interface
    // [1]
    @TransactionAttribute(REQUIRED)
    SessionBean1.method1() {
    // do something...
    Event<myClass>.fire();
    // do something...
    ObserverObject.method2(@Observes(during=AFTER_SUCCESS) myClass) {
    sessionBean2.method2(); // through local bean interface
    @Asynchronous
    @TransactionAttribute(REQUIRED)
    SessionBean2.method2() {
    // do something...
    (with the usual container-managed transaction boundaries)
    ==> the following happens:
    [1] is only reached AFTER the transaction in SessionBean2.method2() finishes! (Although the last statement in SessionBean1.method1() is reached way before that.)
    It's as if SessionBean1.method1()'s transaction somehow isn't "released" (for want of a better word -- it does get committed immediately, before the event handler ObserverObject.method2() is called!) until the asynchronously called Session2.method2()'s transaction finishes as well.
    Does anyone know how I could avoid that?
    (The point of the whole setup would be to have the long-running SessionBean2.method2() run in the background after T1's completion and have SessionBean1.method1() return as soon as possible.)
    P.S.: I have verified that
    a) T1 is committed immediately (the records go in the DB)
    b) SessionBean2.method2() is called asynchronously (control jumps to the next statement in the calling code immediately)
    c) the SessionBean1.method1() doesn't return control to the caller code until T2 finishes
    Thanks,
    Agoston

    there is an error in either one of your web.xml files or in the server.xml..
    it looks like an xml parse error..
    did deploy app changes before this? or update some context stuff within server.xml??

  • Problems with notify/wait on threads

    I have a few Player threads connected to some game server.
    The first player to connect ("Player1") starts a timer to 10 seconds. During this time all other connected players can't do anything. When the 10 seconds are up the game starts.
    My idea is that if the current thread is Player1 then it sleeps for 10 seconds and then calls notifyAll() to wake up all other player threads. Other player threads will wait() until they are notified by Player1. Problem is I can get Player1 to sleep and wake up but my notifyAll() calls don't wake the other players up.
    My basic server connection code:
    // a for loop to create players and add them to a vector ("players"). Run player threads as soon as they connect
    players.add( new Player( server.accept(), maze, this, i + 1);
    players.get(i).start();The run() for Players:
    public void run()
      synchronized( this)
        if( Thread.currentThread().getName.compareTo( "Player1") == 0)
          sleep( 10 * 1000);
          // game_started is a condition var, init to false
          game_started = true;
          notifyAll();
        else
          while( !game_started)
            try
              wait();
            catch( Exception e) {}
    }Somehow my others threads keep waiting even thought the notify signal has been sent. They just keep waiting.
    Any suggestions on what I'm doing wrong?

    Well the problem is that you seem a bit confused over the way wait and notify/notifyAll work.
    Wait (and notify) work with thread against an object monitor. What this means is that you need a common object shared among the threads that they are calling wait/notify on.
    Note that the Javadoc says this about wait
    wait() - Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object.And about notifyAll
    notifyAll() - Wakes up all threads that are waiting on this object's monitor.So the problem is you have these threads waiting and notifying themselves. Which isn't what you want. See this section of [_the concurrency (threading) tutorial_|http://java.sun.com/docs/books/tutorial/essential/concurrency/guardmeth.html] for more on how to use wait/notify/notifyAll.

  • Notify & wait

    Here is a snip of my code :
    public void start()
       setVisible(true);
       long wait_time;
       for (int counter = 0; counter < 10; counter++)
          try
             wait = false;
             wait_time = (long) ((Math.random() * 15000)+5000);
             Thread.sleep(wait_time);
             t1.start_timer();
             // some code
             Thread.wait();
             t1.stop_timer();
          catch (InterruptedException e)      {}
    public void wait_finished()
       Thread.notify();
    }When I run the wait_finished() method I get "non-static method wait() cannot be referenced from a static context" error message. Any ideas what Im doing wrong ?

    You can only call wait on an object if you own that objects lock.
    Try this.
    Thanks for your prompt reply jboozer.
    I change my code like you said, now it looks something
    like this :
    public void start()
    setVisible(true);
    long wait_time;
    for (int counter = 0; counter < 10; counter++)
    try
    wait = false;
    wait_time = (long) ((Math.random() *
    m() * 15000)+5000);
    Thread.sleep(wait_time);
    t1.start_timer();
    synchronized
    wait();
    // some code
    t1.stop_timer();
    catch (InterruptedException e)      {}
    public void wait_finished()
    synchronized
    notify();
    The above compiles ok, but when I run the code I get
    an error when try to execute wait();
    "java.lang.IllegalMonitorStateException : current
    thread not owner " - error message
    What does this mean ?
    Cheers for any help.

  • Need help with notify() / wait() synchronization problem.

    I am trying to overcome a race condition that seems to be coming from the use of the swing ui file chooser in my code. I tried to solve this problem using wait/notify but I ended up in an infinite loop so and was wondering if anyone could help me out. Here are some code snipets:
    //Create a new monitor
    final private Object monitor = new Object();
    //in method getAppletdirectory()
    synchronized(monitor)
    //initialize the wizard which is a filechooser then call using the swingui showCenteredDialog
    DialogUtils.showCenteredDialog(wizard, -1, -1);
    monitor.notifyAll();
    //return some info from the wizard
    // in main method of this class
    File appletDirectory = getAppletDirectory(controller);
    synchronized(monitor) {
    try
    monitor.wait();
    catch (InterruptedException e){
    The method causes in infinite loop, I believe this is happening because the notify is being called before the dialog window has completed then when the wait is set up there is no notify to come. My problem is the wizard is used in other circumstances where it will not look for this. Would it be okay to add the notify() to the wizard's functionality even though sometimes there will be no monitor waiting for it? Can anyone give me any advice on this? Thanks.

    >
    The reason I believe this was a race condition is because when I run this code without the synchronized call and the DialogUtils.showinfoDialog commented out as shown below. When the zip occurs some of the files do not show up in the newly created .zip. But if I uncomment the dialog call then the .zip contains everything I expect it to.
    >
    Okay, so let's restate this:
    Problem
    I try to zip a file, but when I try to run the code above, then some of the files don't make it to the Zip archive. Some do, some don't.
    Diagnostics
    I notice when I call DialogUtils.showinfoDialog then the zip is formed properly. I think this is because the showinfoDialog method makes the user click on a button before returning. So my concern is that I am generating a race condition by <doing something... I have no idea what...>.
    Okay, so now we have that out of the way, You also say "Also, the reason I think this is an infinite loop is because when I added the synchronized calls and it gets to this part of the program it hangs and must be force quit." For there to be an infinite loop, there first has to be a loop, then there has to be a condition for ending the loop that never is reached. I still see no loop in your code, so it is impossible to have an infinte loop in any code that you have shown (there may be an infinite loop someplace else that you aren't showing). That said, your computer can hang for any number of other reasons, including any un-interrupted blocking operation (reading from a Stream, waiting on a BlockingQueue, calling wait() without notify()), or a deadlock situation. The problem with saying that you have an infinite loop is that the first thing to do to fix that is to look at the loop. If you don't know what is causing a hang, just say 'The program is hanging here.' That way we can look at different reasons for hangs, rather than getting caught up in a red herring of an infinite loop.
    Okay, down to the problem:
    1) Why are you including any synchronization? Why do you think you need it? How many Threads do you create? And where?
    2) We can't help you with the code you provided. It tells us nothing about what is going on. What is DialogUtils? FileUtils? RistrettoWizard? No clue. Don't know what any of those methods do. What context is this method called in? Why the synchronization?
    What you need to do is generate a short, working sample that shows the problem. Read [this site for examples.|http://sscce.org/] Make it simple, and complete. If I can't copy the code and run it to see your problem then I can't help diagnose it.

  • Observer Pattern Help

    hi,
    I am trying to understand how and when you would use an observer pattern. I understand that it allows one class to observe another, i.e if a variable was to change in 1 class all observing classes would be notified of the change. I do not understand how u would implement this, I have seen some examples but they are kinda confusing does anybody have a simple way of showing how this pattern is implemented?
    thx
    sbains

    Dish would be the observable in this case. Waiter and Chef are the /
    contain observers. The observer's update method will get called whenever
    the observable calls notifyObservers.
    public class Dish extends Observable {
        public void setStock(int stock) {
            .. business logic ..
            this.setChanged();
            this.notifyObservers(new Integer(stock));
    public class Waiter implements Observer {
        public void update(Observable o, Object arg) {
            Long stock = (Long) arg;
            .. business logic ..
    }Note that Listeners are also implementations of the Observer pattern, if
    that helps any.

  • READ THIS if you use the observer APIs ...

    This is just a heads up for developers who take advantage of
    the observer APIs in Spry. For the next version of Spry I plan on
    making the observer APIs for both the Data Set and the Dynamic
    Region consistent.
    Currently in Spry PR 1.1 the data set observer mechanism
    requires that you register an object with an onDataChanged method
    on it. This method is then called with a notification type
    (Spry.Data.DataSet.ODC_*) which developers have to manually check
    against and conditionally perform their action.
    In Spry PR 1.1, the observer mechanism used for the dynamic
    region requires that you register a callback function, which gets
    passed a region state (Spry.Data.Region.RS_*) whenever it is
    called, and it is up to the developer to check against the region
    state and conditionally perform their action.
    For the next release of Spry, I plan to move to the following
    model:
    - Both data set and region observer mechanisms will require
    an object which defines notification methods for which it wants to
    be notified for.
    // Create an object with notification methods.
    var myObserver = new Object;
    myObserver.onDataChanged = function (notifier, data) {
    alert("OnDataChanged called!"); };
    // Register your object as an observer on the data set.
    dsMyDataSet.addObserver(myObserver);
    - Notification methods will all have the same signature:
    function (notifier, data) {}
    The notifier is the object that is dispatching the
    notification, and the data is an object that will contain
    information regarding the notification, where necessary, or
    undefined if no additional data is necessary for the notification.
    When called, the 'this' object within the notification method
    will be the actual observer object.
    - We will publish a list of notification methods that can be
    defined on the observer object for both the data set and dynamic
    region.
    - *All* methods on the observer object are *OPTIONAL*, which
    means you only have to define the notification methods that you
    want to be called for. For example:
    var observerA = new Object;
    var observerB = new Object;
    observerA.onDataChanged = function (notifier, data) {
    alert("observerA.onDataChanged called!"); };
    observerA.onSortChanged = function (notifier, data) {
    alert("observerA.onSortChanged called!"); };
    observerB.onDataChanged = function (notifier, data) {
    alert("observerB.onDataChanged called!"); };
    myDataSet.addObserver(observerA);
    myDataSet.addObserver(observerB);
    In the example above both observerA and observerB will be
    called whenever the data changes, but only observerA will be
    notified whenever a sort happens.
    - Some events will have pre and post notifications. For
    example onPreLoad(), onPostLoad(), onPreUpdate() and
    onPostUpdate(), etc.
    If you have any opinions, concerns or feedback on this. Now
    would be the time to speak up.
    --== Kin ==--

    As one person who asked for this, I like what your planning.
    Is that onPreLoad() an event that will get fired before an Ajax
    request goes out for new data? Cuz I could really use that.
    A tagentally related thought: Notifications are great, but in
    some cases, I might want to control whether some behavior happens.
    Say, perhaps I want to control whether the load actually happens.
    In that case, I'd want a delegate object, which would have some
    methods on it that could cancel the event that is going happen.
    Just as an example:
    var delegate = {
    willFireLoad: function(...) { if (somecondition) return
    false; else return true; },
    unknownValueForKey: function(key, dataset) { ... return
    dynamic value ... },
    unknownValue_desc: "Description"
    dataSet.setDelegate(delegate);
    The first would allow me to stop the data from being loaded.
    The second would allow me to return a value for a key that isn't
    present in the dataset. And the third could be a way to hardcode a
    value for the key 'desc'.
    Just kinda an idea as far as what could be done, and I'm sure
    there might be other control points too.
    -d

  • About observer pattern

    i have some question about the issue of delay time. for example, i have a web base live quote stock system. you know that every time the stock value is changing, once the stock was changed, each clients will update the stock value immediately. If i use observer pattern to apply the system, the subject will montoring the new stock value which is come from other resource, once the new value is updated, it will notify it's observer to update the value. If i have a hundred, a thoursand.. clients/observer which may be stored in a list. then some client will notify immediately and some are not. Is it right? if the concept is right, is there any solution to solve the issues? Thanks.

    Let me know if I understand your question:
    - you mean if your subject notifies all its observers one by one sequentially in the same thread, then the "last in line" will be notified long after the fist one.
    - plus, if one observer takes a long time to process the notification, subsequent observers may not receive their notification before a while.
    Well, yes, this is a known problem. A well-known incarnation is listeners processing event in a single event-dispatching thread in AWT or Swing: if one listener takes a long time to complete processing the notification, then all subsequent listeners do not receive the notification in time; worse all other graphical events are blocked, and the UI display freezes, because even the repaint events are pending the first listener method to return.
    In Swing the way around this is to ask listener classes to observe a convention: complete quickly all listeners methods - if a time-consuming job must be started as part of processing a notification, spawn another thread for it.
    If you don't trust the observers to observe this convention (you may not be the author of all observers code, or your observers are in different JVMs), then you have no option other to spawn multiple threads:
    one thread per observer
    or, a pool of dispatching threads
    or, a pool of dispatching thread with support for timeouts (there is no generic way to reclaim a thread that is timeouting, but you can choose to have a master thread that monitors dispatching threads for timeout and uses the pool as dispatching threads are timeouting).

  • Reverse observer pattern

    hi,
    is it possible to use the reverse of observer pattern
    i.e - observer pattern is described normally as there is 1 subject & many observers.
    So when the subject changes, it notifies the observers. My problem is I only 1 observer but many things change, so when each of the things (subjects ) change I want to call the observer to get the updates.
    Is it possible?
    What if the each subject is run in a thread.?
    Thank you

    is it possible to use the reverse of observer pattern
    i.e - observer pattern is described normally as there
    is 1 subject & many observers.
    So when the subject changes, it notifies the
    observers. My problem is I only 1 observer but many
    things change, so when each of the things (subjects )
    change I want to call the observer to get the
    updates.
    Is it possible?Yes. Rather than have classes A, B, C register as listeners on class D, have class D register itself as a listener on classes A, B, C. Whenever A, B, or C do something, they'll notify all classes observing them (namely D).
    This is not the inverse of observer pattern but rather a different way of utilizing it than what you have described in your question.
    >
    What if the each subject is run in a thread.?
    If classes A, B, C run in separate threads, the pattern implementation does not change too terribly much. Whenever A, B, C do something they will still notify their observers (namely D). But you should realize that since they are multithreaded you may encounter a time when A and B notify D simultaneously. You will need to think about synchronization.

  • Thread sends notify() before waiting thread says wait()

    In the code below the ref book I'm using "Sun certified Programmer for Java 2" had the calculator thread starting before the Reader thread was even created and hence the calculator thread was finished it's task and sending a notify() before the Reader even had it's socks on and saying wait()
    ( And this cost me a lot of time tryin to figure this problem out as the code must have being written for a Z80 processor and not a 2.4GHz P4)
    To fix this I put the calculator starting after the reader thread, but .......
    I would have thought that java would have some protection against this happening, ie, like a notify flag which a thread can set if it has done it's job BEFORE the waiting thread even starts waiting, ie a preemptive mechanism to help speed things up ?
    package MyPackage;
    public class Reader extends Thread {
    Calculator MyCalculator;
    public Reader(Calculator calc){
    MyCalculator = calc;
    public void run(){
    synchronized(MyCalculator){
    try{
    System.out.println("Waiting for calculation ... ");
    MyCalculator.wait();
    }catch (InterruptedException e){}
    System.out.println("Total is: " + MyCalculator.total);
    public static void main(String args []){
    Calculator calculator = new Calculator();
    //calculator.start();
    new Reader( calculator ).start();
    calculator.start();
    package MyPackage;
    public class Calculator extends Thread{
    int total;
    public void run(){
    synchronized(this) {
    for(int i=0; i<100; i++){
    total += i;
    System.out.println("Calculation complete, notifying waiting thread..");
    notify();

    It's up to the 'umble programmer to code it right. The code you quoted was crap.
    The most common way to wait is on a condition:
    while (hotAndBotherd())
        obj.wait();And then the notifying thread will take steps to change that:
    //code that cools off the hot and bothered
    obj.notify[all]();If the initial state of things is hot and bothered then there is no race condition: the first thread will wait.

  • What about post notify?

    Hi to everybody,
    I've got a doubt related to the notify (or notifyAll) method. What happens after a thread calls notify? The monitor theroy states that the thread should be temporary suspended, granting the access to the resumed thread. Once the latter has finished the notifier thread (suspended into an urgent queue) should be resumed in order to conclude its execution (i.e., to do the code after the notify call).
    Nevertheless, debugging a program that apparently misbehaves, I noticed that after a notify call the notifier thread does not seem to suspend itself.
    With this suspect I read the documentation for the java.lang.Object#notify method, and I found:
    The awakened thread will not be able to proceed until the current thread relinquishes the lock on this object. The awakened thread will compete in the usual manner with any other threads that might be actively competing to synchronize on this object; for example, the awakened thread enjoys no reliable privilege or disadvantage in being the next thread to lock this object.
    that means that the resumed thread is only resceduled, but it does not start its execution immediatly. Is this right? Can anybody give me some details about the exact behavior of the notify/wait thread scheduling?
    Thanks,
    Luca

    [url http://forum.java.sun.com/thread.jsp?thread=466588&forum=31]Cross-post. Please read one of the many guides to forum etiquette to see why that's unpopular. For example, http://pjt33.f2g.net/javafaq/posting.html

  • User events vs notify event

    I've read a number of whitepapers on User Events and Notify/Wait on Notification.  They seem quite similar to me, and I'm not sure which to use.  I have (well, when I write it) a transmit/receive VI that I think will be running in a separate thread.  It's supposed to listen for TCP/IP (rx) messages and "notify" (I use that generically here) a test that's waiting for this message.  That test would access some Shared Variable, or user-defined data to extract/process the message.  I will (possibly) then build a message (in another shared variable) response, and "notify" the tx routine that it has something to send.  I (obviously) don't have all of this worked out, but I'm assuming right now that I need to open and keep open the TCP/IP socket because it' going to be a secure (https/ssl) channel.  That's why I thought I would make this a separate thread.  With this in mind, is User Event or notifier more suitable or even the right approach?

    Based on your description I would recommend that you use queues to pass your messages through the system. Queues are similar to notifies with one major difference. With queues you can stack up multiple messages to be processed. With a notifier you only get a single message. The event structure works best for UI types events. Though you can define your own events I don't think the event structure would be the best option for your situation. However you could still use an event structure for processing your UI events.
    Mark Yedinak
    "Does anyone know where the love of God goes when the waves turn the minutes to hours?"
    Wreck of the Edmund Fitzgerald - Gordon Lightfoot

  • Performance degradation on multi-processor computer

    I saw couple similar topics but they are not the same. The issue is that .NET app is not so affected and Java app. See below. Thank you.
    There is strange picture is observed here. The same test, the same data - the more CPUs computer has, the slower test results:
    1) Powerful 8 CPUs server with 1 CPU assigned to process via "Set Affinity" in Task Manager: 1578 ms
    2) Powerful 8 CPUs server with 2 CPUs assigned to process via "Set Affinity" in Task Manager: 1656 ms
    3) Powerful 8 CPUs server with no adjusments via Task Manager - all 8 CPUs are enabled: 3469 ms
    4) Those tests 1-3 were on powerful server. On my less powerful laptop with single core set in BIOS I get: 921 ms (!!!) How come?
    The test has 2 active threads. First one puts 5,000,000 updates into queue. Second thread at the same time pops updates from our queue. Source is provided.
    With more sophisticated test that I cannot provide I have performance difference much more noticable. That test has more synchronize calls.
    The only 2 explanations that I can think of are:
    1) Necessity to synchronize CPU caches on all possible CPUs. But why would computer need to synch all 8 CPUs if only 2 threads are using that data - meaning at most only 2 CPUs are active.
    2) Windows Task Scheduler switches current CPU for given activ thread all the time. But why would it does so if it makes more powerful server only worse?
    I hope there is some good explanation for this behavior. And the most important - there is a solution for our server to really beat my laptop performance counter.
    By the way the same type of sample in .NET v.2.0 (also provided) with x64 binary runs 546 ms on my laptop and 781 and 813 ms on server with affinity to 1 and to 1-8 CPUs respectively. It makes me think this issue is JVM related. Please, comment.
    == ThreadBoundaryQueue.java file ==
    import java.text.NumberFormat;
    import java.util.ArrayDeque;
    public class ThreadBoundaryQueue
        private static final int COUNT = 5*1000*1000;
        private static final int delayBeforeStart = 10;
        private static void print(String text)
                    System.out.println(Thread.currentThread().getName() + ": " + text);
        public static void main(String[] args) throws Exception
                    SysInfo.dump();
                    print("Preparing data for test...");
            Long events[] = new Long[COUNT];
            for(int i = 0; i < COUNT; ++i)
                events[i] = new Long(i/87);
            final Object notifier = new Object();
            final boolean finished[] = new boolean[1];
            SimpleEventQueueWithArrayDeque queue = new SimpleEventQueueWithArrayDeque(new IEventDispatcher<Long>()
                long sum_;
                int count_;
                @Override
                public void dispatchEvent(Long event)
                    for(long l = event.longValue() * 50; l > 0; l /=17)
                        sum_ += l;
                    if(++count_ == COUNT)
                        synchronized (notifier)
                           finished[0] = true;
                           notifier.notify();
                           print("some dummy sum is " + sum_);
            queue.startDispatching();
            print("Test starts in "+delayBeforeStart+" seconds");
            print("================================");
            Thread.sleep(delayBeforeStart*1000);
            print("Started...");
            TimeCounter sendingTime = new TimeCounter();
            TimeCounter processingTime = new TimeCounter();
            for(int i = 0; i < COUNT; ++i)
                queue.postEvent(events);
    sendingTime.dump("sending of " + COUNT + " events");
    synchronized (notifier)
    while(!finished[0])
    notifier.wait(1);
    processingTime.dump("processing of " + COUNT + " events");
    print("...Done");
    queue.stopDispatching();
    private static class SysInfo
    public static void dump()
    for(String p : new String[]{
    "os.name",
    "os.version",
    "os.arch",
    "sun.arch.data.model",
    "java.runtime.version",
    "java.vm.name",
    }) print(p+"="+System.getProperty(p));
    print("CPU count=" + Runtime.getRuntime().availableProcessors() + "\n");
    private static class TimeCounter
    private long start_;
    public TimeCounter()
    start_ = System.currentTimeMillis();
    public void dump(String name)
    print( name
    + " took, milliseconds: "
    + NumberFormat.getIntegerInstance().format(System.currentTimeMillis()-start_));
    private interface IEventDispatcher<EventType>
    void dispatchEvent(EventType event);
    private static class SimpleEventQueueWithArrayDeque implements Runnable
    private ArrayDeque<Long> buffer_;
    private Thread thread_;
    private IEventDispatcher<Long> dispatcher_;
    public SimpleEventQueueWithArrayDeque(IEventDispatcher<Long> dispatcher)
    buffer_ = new ArrayDeque<Long>(65535);
    dispatcher_ = dispatcher;
    public void postEvent(Long event)
    synchronized (buffer_)
    buffer_.addLast(event);
    buffer_.notify();
    @Override
    public void run()
    try
    Long event;
    while(!Thread.interrupted())
    synchronized (buffer_)
    event = buffer_.poll();
    while(event == null)
    buffer_.wait(300);
    event = buffer_.poll();
    dispatcher_.dispatchEvent(event);
    catch(InterruptedException ex)
    public synchronized void startDispatching()
    if(thread_ == null)
    thread_ = new Thread(this, "queue dispatcher");
    thread_.setDaemon(false);
    thread_.start();
    public synchronized void stopDispatching()
    if(thread_ != null)
    thread_.interrupt();
    try
    thread_.join();
    catch(Exception ex){}
    thread_ = null;

    No problem. We are pretty sure in what we see. We repeated a test. So, new test makes 5 rounds of test with 5,000,000 updates. And then it makes another 20 rounds that are counted. Results with our process having "Real-time priority" in both cases:
    8 CPUs on 8 CPUs server: 40.5 seconds
    1 CPU on the same 8 CPU server: 17,9 seconds
    Just to add more confidence in results we made the same with our PRODUCTION system that has 4 heavy processes on 8 CPUs server. We set affinity for each process to have 2 of 8 CPUs. It made heavy loaded system to take around half less CPU time (each of 4 processes with a lot of "synchronized" calls). How to explain this and how to configure our system with that knowledge? And why Windows and/or JVM does not do this for us?
    Code is below. Thank you
    import java.text.NumberFormat;
    import java.util.ArrayDeque;
    public class ThreadBoundaryQueue {
        private static final int COUNT = 5*1000*1000;
        private static final int delayBeforeStart = 15;
        private static Long Events_[];
        private static void print(String text) {
            System.out.println(Thread.currentThread().getName() + ": " + text);
        public static void main(String[] args) throws Exception
            SysInfo.dump();
            final Object notifier = new Object();
            final boolean finished[] = new boolean[1];
            IEventDispatcher<Long> d = new IEventDispatcher<Long>() {
                long sum_;
                int count_;
                @Override
                public void dispatchEvent(Long event) {
                    for(long l = event.longValue() * 50; l > 0; l /=17) {
                        sum_ += l;
                    if(++count_ == COUNT) {
                        synchronized (notifier) {
                            finished[0] = true;
                            print("some dummy sum is " + sum_);
                            sum_ = 0;
                            count_ = 0;
                            notifier.notify();
            print("Preparing data for tests...");
            Events_ = new Long[COUNT];
            for(int i = 0; i < COUNT; ++i) {
                Events_ = new Long(i/87);
    print("Test starts in "+delayBeforeStart+" seconds");
    print("================================");
    Thread.sleep(delayBeforeStart*1000);
    print("BEGIN Warmup...");
    for(int i = 0; i < 5; ++i) {
    print("Test " + (i+1) + "...");
    test(new SimpleEventQueueWithArrayDeque(d), notifier, finished);
    print("END Warmup...");
    TimeCounter allTime = new TimeCounter();
    for(int i = 0; i < 20; ++i) {
    print("Test " + (i+1) + "...");
    test(new SimpleEventQueueWithArrayDeque(d), notifier, finished);
    print("...Done");
    allTime.dump("ALL TESTS after warm up");
    private static void test(SimpleEventQueueWithArrayDeque queue, Object notifier, boolean[] finished) throws Exception {
    synchronized (notifier) {
    finished[0] = false;
    queue.startDispatching();
    print("Started...");
    TimeCounter sendingTime = new TimeCounter();
    TimeCounter processingTime = new TimeCounter();
    for(int i = 0; i < COUNT; ++i) {
    queue.postEvent(Events_[i]);
    sendingTime.dump("sending of " + COUNT + " events");
    synchronized (notifier) {
    while(!finished[0]) {
    notifier.wait(100);
    processingTime.dump("processing of " + COUNT + " events");
    queue.stopDispatching();
    private static class SysInfo {
    public static void dump() {
    for(String p : new String[]{"os.name", "os.version", "os.arch",
    "sun.arch.data.model", "java.runtime.version", "java.vm.name",})
    print(p+"="+System.getProperty(p));
    print("CPU count=" + Runtime.getRuntime().availableProcessors() + "\n");
    private static class TimeCounter {
    private long start_;
    public TimeCounter() {
    start_ = System.currentTimeMillis();
    public void dump(String name) {
    print( name
    + " took, milliseconds: "
    + NumberFormat.getIntegerInstance().format(System.currentTimeMillis()-start_));
    private interface IEventDispatcher<EventType> {
    void dispatchEvent(EventType event);
    private static class SimpleEventQueueWithArrayDeque implements Runnable {
    private ArrayDeque<Long> buffer_;
    private Thread thread_;
    private IEventDispatcher<Long> dispatcher_;
    public SimpleEventQueueWithArrayDeque(IEventDispatcher<Long> dispatcher) {
    buffer_ = new ArrayDeque<Long>(65535);
    dispatcher_ = dispatcher;
    public void postEvent(Long event) throws Exception {
    synchronized(buffer_) {
    buffer_.addLast(event);
    buffer_.notifyAll();
    @Override
    public void run() {
    try {
    Long event;
    while(!Thread.interrupted()) {
    synchronized(buffer_) {
    event = buffer_.poll();
    while(event == null) {
    buffer_.wait(100);
    event = buffer_.poll();
    dispatcher_.dispatchEvent(event);
    catch(InterruptedException ex){}
    public synchronized void startDispatching() {
    if(thread_ == null) {
    thread_ = new Thread(this, "queue dispatcher");
    thread_.setDaemon(false);
    thread_.start();
    public synchronized void stopDispatching() {
    if(thread_ != null) {
    thread_.interrupt();
    try {
    thread_.join();
    catch(Exception ex){}
    thread_ = null;

  • About Threads help! help!

    my lock can not work as my expecked,the key code segments as follows:
    code segment1 and code segment2 belong to different threads, when the segment1 get the observer's lock the segment2 should stop because of lacking of resource. but the true testing result is
    when ran into offset() ,the segment2 got resource ,and ran. the two segments has the same object ,but it can't synchronize ,i don't know why. help!help!
    code segment 1:
    synchronized (observer)
    if (offset() == 0)
    System.out.println("success&#65281;&#65281;&#65281;");
    observer.cleanCounter();
    //wait
    try
    observer.wait();
    catch (InterruptedException ex1)
    code segment 2:
    synchronized(observer){
    observer.increase() ;
    System.out.println("increase!") ;
    if(observer.isLimited()){
    observer.notify() ;
    System.out.println("notify!") ;

    ok!
    private int offset()
    //System.out.println("enter offset!") ;
    DB db = new DB();
    String sql = "select log_id,softSN,SMS_content,audit_state"
    + " from SMS_content"
    + " where audit_state != 'n'";
    ResultSet rs = null;
    try
    //System.out.println(sql) ;
    rs = db.executeQuery(sql);
    if (rs == null)
    return -1;
    while (rs.next())
    String auditState = rs.getString("audit_state");
    String softSN = rs.getString("softSN");
    String smsContent = rs.getString("SMS_content");
    String logId = rs.getString("log_id");
    //&#26410;&#36890;&#36807;&#23457;&#26680;
    if (auditState.equals("d"))
    //&#25554;&#20837;&#23457;&#26680;&#22833;&#36133;&#34920;
    System.out.println("enter deny!");
    String sqlInsert =
    "insert into audit_fail(softSN,log_id,SMS_content)"
    + "values('" + softSN + "'," + logId + ",'" + smsContent + "')";
    if (db.executeUpdate(sqlInsert) != 1)
    return -1;
    // System.out.println("success!") ;
    //&#20174;SMS_content,SMS_cache&#34920;&#20013;&#21024;&#38500;&#25968;&#25454;
    String sqlDel = "delete from SMS_content where log_id=" +
    logId;
    if (db.executeUpdate(sqlDel) != 1)
    return -1;
    sqlDel = "delete from SMS_cache where log_id=" +
    logId;
    if (db.executeUpdate(sqlDel) != 1)
    return -1;
    // System.out.println("sucsess2!") ;
    //&#23457;&#26680;&#36890;&#36807;
    else
    // System.out.println("inter permit!") ;
    Queue queue = new Queue();
    //System.out.println(queue.i + " i&#25351;&#20026;");
    //System.out.println(Integer.parseInt(logId) + " logId");
    ResultSet rsSMSContent = queue.getSMSContent(Integer.parseInt(logId));
    // System.out.println(rsSMSContent + " dddddddddddd");
    Enterprise enterprise = new Enterprise();
    int enterID = enterprise.getEnterID(softSN);
    // System.out.println(enterID + " aaaaaaaaa");
    PropertiesFile file = QueueCount.getInstance();
    // System.out.print(file + " bbbbbbbb");
    int defaultPriority = enterprise.getEnterDefaultPriority(softSN);
    //System.out.println(defaultPriority + " cccccccccc");
    int createResult = -1;
    if (defaultPriority != 3)
    createResult = queue.createQueue(rsSMSContent,
    Integer.parseInt(logId), enterID,
    file, defaultPriority);
    // System.out.println("createResult"+createResult) ;
    // System.out.println("into queue") ;
    else
    createResult = queue.createQueue(rsSMSContent,
    Integer.parseInt(logId), enterID,
    file, 2);
    //System.out.println("createResult"+createResult) ;
    // System.out.println("into queue") ;
    rsSMSContent.close();
    queue.close();
    if (createResult == 0)
    String sqlDel = "delete from SMS_content where log_id=" + logId;
    // System.out.println("sql1") ;
    if (db.executeUpdate(sqlDel) != 1)
    return -1;
    sqlDel = "delete from SMS_cache where log_id=" + logId;
    if (! (db.executeUpdate(sqlDel) >= 1))
    return -1;
    // System.out.println("sql2") ;
    return 0;
    catch (Exception e)
    e.printStackTrace();
    return -1;
    finally
    try
    if (rs != null)
    rs.close();
    db.close();
    catch (SQLException ex)

  • Multithreading issue with Client/Server chat program

    In a nutshell, I just recently starting attempting to use Sockets and decided I wanted to give a go at a chat program. I have some experience with threads but I know little about how to find and fix multithreading issues. I think this is my problem right now since I am deadlocking while connecting and disconnecting client-side ... and updates about connection status of a client are not always displaying correctly server-side.
    [ Code Snippet|http://snipplr.com/view/15206/clientserver-chat-program/]
    Thanks for the help

    NOTE: all catch clauses have been omitted for clarity. They all just perform System.err.println() with the msg embedded
    Very valid point. I cut out the GUIs and just tried having the Server/Client communicate. I am still having concurrency issues. This is my first attempt at synchronized methods and locking objects so go easy on me if I did something(s) noob =D
    public class MySocket
        public static final String QUIT = "~~QUIT~~";
        private ObjectOutputStream out;
        private ObjectInputStream in;
        private Socket conn;
        public MySocket(String ip)
            obsList = new ArrayList<IClientObs>();
            try
                conn = new Socket(ip, 5000);
                if (conn.isConnected())
                    out = new ObjectOutputStream(conn.getOutputStream());
                    in = new ObjectInputStream(conn.getInputStream());
        public synchronized String nextMsg()
            String msg = "";
            try
                synchronized(in)
                    msg = (String)in.readObject();
                    notify(msg);
            return(msg);
        public synchronized boolean sendMsg(String msg)
            boolean sentMsg = false;
            try
                synchronized(out)
                    if (out != null)
                        out.writeObject(msg);
                        out.flush();
                        sentMsg = true;
            return(sentMsg);
        public synchronized void closeConn()
            try
                synchronized(this)
                    sendMsg(QUIT);
                    conn.close();
                    out.close();
                    in.close();
        public synchronized Socket getConn()
            return(conn);
        public synchronized ObjectOutputStream getOutStream()
            return(out);
        public synchronized ObjectInputStream getInStream()
            return(in);
       //Observer Pattern implemented below   
    public class Server extends Thread
        public static final int MAX_CLIENTS = 2;
        public static final String QUIT = "~~QUIT~~";
        private ServerSocket server;
        private ArrayList<ConnClient> conns;
        private int connCount;
         * Constructor for objects of class Server
        public Server()
            conns = new ArrayList<ConnClient>();
            obsList = new ArrayList<IServerObs>();
            connCount = 0;
        public void startNow()
            this.start();
        public void run()
            runServer();
        public synchronized void runServer()
            try
                setup();
                while (true)
                    waitForConn();
                    processComms();
        private synchronized void setup() throws IOException
            server = new ServerSocket(5000);
            notify("Server initialized.\n");
        private synchronized void waitForConn() throws IOException
            if (connCount < MAX_CLIENTS)
                notify("Waiting for connection...\n");
                Socket conn = server.accept();
                if (conn.isConnected())
                    conns.add(new ConnClient(conn));
                    notify("Client connected @ '" + conns.get(connCount).getIP() + "'.\n");
                    connCount++;
            else
                notify("Connection request rejected; max connections have been reached.\n");
        private synchronized void processComms() throws IOException, ClassNotFoundException
            //Receive any msgs sent by clients and forward msg to all clients
            for(ConnClient rcvClient : conns)
                String msg = rcvClient.nextMsg();
                //if client quit, then close connection and remove it from list
                if (msg.equals(QUIT))
                    notify("Client disconnected @ '" + rcvClient.getIP() + "'.\n");
                    rcvClient.closeConn();
                    conns.remove(rcvClient);
                    connCount--;
                else
                    for(ConnClient sndClient : conns)
                        sndClient.sendMsg(msg);
        public synchronized void shutdown()
            try
                server.close();
                for(ConnClient client :conns)
                    client.closeConn();
       //Observer Pattern implemented below
    }I also found another issue that I haven't thought up a way to deal with yet. When the user starts the program the follow line is executed "conn = server.accept();" which halts execution
    on that thread until a connection is established. What if the user wants to stop the server before a connection is made? The thread keeps running, waiting for a connection. How do I kill this thread?
    On this last issue (I figured by adding the follow code to my action listener inside of my server gui I could stop the thread safely but it's no good so far)
    public void actionPerformed(ActionEvent e)
            Object src = e.getSource();
            if (src == strBtn)
                if (server == null)
                    strBtn.setEnabled(false);
                    stpBtn.setEnabled(true);
                    server = new Server();
                    server.addObserver(this);
                    server.start();
                else
                    console.append("Console: Server is alread initiated.\n");
            else if (src == stpBtn)
                synchronized(server)
                strBtn.setEnabled(true);
                stpBtn.setEnabled(false);
                server.shutdown();
                server = null;
                console.append("Console: Server has been stopped.\n");
        }Edited by: mcox05 on May 21, 2009 10:05 AM
    Edited by: mcox05 on May 21, 2009 10:17 AM
    Edited by: mcox05 on May 21, 2009 10:58 AM
    Edited by: mcox05 on May 21, 2009 11:01 AM
    Edited by: mcox05 on May 21, 2009 11:03 AM
    Edited by: mcox05 on May 21, 2009 11:03 AM

Maybe you are looking for

  • HT2534 why isn't there 'None' in the payment method in my iphone? I could not skip it. Please help

    why isn't there 'None' in the payment method in my iphone? I could not skip the billing info. Please help

  • How to change 'created by' name in the smartform

    Hi, I have copied one standard smartform into Z_smartform. My z_smartform is having 'created by' name as in standard smartform. Could anyone please tell me how to change that name to my name. Thank you, Regards, Kusuma.

  • Radius Authentication in ACS 5.2 with AD

    Friend, I have a questión about radius authenticaction with AD, when I log in into the network with user in AD and I make a mistake in password my radius authenticaction event in ACS 5.2 dont show me this logg. only show the authentication succeeded

  • Saving a template

    I would like to be able to write an e-mail and save it as a template. I tried "save as" in the "file" menu but it's not selectable for some reason. Does anyone know how to make a template to I don't have to re-write or copy and paste from a pages doc

  • How to generate license for AIP-SSM without PAK-number?

    Hello! I'm sorry for my English. I have a problem with generating license for AIP-SSM. My contract with SMARTnet service is activated, but I don't have a PAK-number. How I can generate a license for updating my module?