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.

Similar Messages

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

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

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

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

  • How to insert queue element from C

    I want to insert a single queue element into a LabView Queue from C (from a DLL).
    The only thing I found is How to set an Labview-Occurence from C. I assume that I have to do that in 2 steps: 1. copy the string data into the queue with a push/pop command. 2. Set the Occurence from the queue to notify waiting queue elements.
    I only need to know how to realize this in the exactly way. (internals of Queue handling, Queue structure, example code, ....)
    I'm using LabView 6.0.2 with WinNT 4.0
    Thank's for help.
    Robert

    Robert,
    You currently cannot access Queue elements from external code. We hope to add this feature to a future version.
    Marcus Monroe
    National Instruments

  • Does notifyAll() wake up all the threads?

    If I got 4 threads which are in waiting status (wait()) .Does notifyAll() really wake up all the threads?
    Can anyone tell me more about "object lock"?

    look left to the API's!
    my bold
    notifyAll
    public final void notifyAll()Wakes up all threads that are waiting on this object's monitor. A thread waits on an object's monitor by calling one of the wait methods.
    The awakened threads will not be able to proceed until the current thread relinquishes the lock on this object. The awakened threads will compete in the usual manner with any other threads that might be actively competing to synchronize on this object; for example, the awakened threads enjoy no reliable privilege or disadvantage in being the next thread to lock this object.
    This method should only be called by a thread that is the owner of this object's monitor. See the notify method for a description of the ways in which a thread can become the owner of a monitor.
    Throws:
    IllegalMonitorStateException - if the current thread is not the owner of this object's monitor.
    See Also:
    notify(), wait()

  • Need help stopping a thread

    I have a thread that starts a file download. I tried using the following.
    On the mouse click event of a button
    thread.interrupt();
    in the file download method
    if(!thread.isInterrupted())
    do stuff
    else
    thread.interrupted();
    The way it stands now, the file download stops and everything seems fine. But I cant restart the thread. I read something about having to return from the run method but I cant get that to work.
    Thanks,
    Jason

    interrupt is not a replacement for the deprecated stop. It performs interruption of waits and blocks. And sets a flag the next time the code in the thread hits a wait or block.
    Your if else logic is unsafe wrt the use of interrupt.
    You need to change the code to depend on a synchronized object with wait and notify
    For example in the thread follow the motionObject:
        public LocateSampleThread(AerotechWrapper aerotechWrapper, double xScale, double yScale, double zScale, double &#966;Scale)
            this.aerotechWrapper=aerotechWrapper;
            //this.xScale=xScale;
            //this.yScale=yScale;
            //this.zScale=zScale;
            //this.&#966;Scale=&#966;Scale;
            this.motionObject=new Object();
            alarmEventListeners=new java.util.Vector();
            recoveredAlarmEventListeners=new java.util.Vector();
        public void run()
            int loopCount=0;
            while(!abort)
                try
                    synchronized(motionObject)
                        motionObject.wait();
                        stop=false;
                    if(abort) break;
                    StateModel.getInstance().setState(StateModel.MOVING);
                    try
                        StateModel.getInstance().setActive(StateModel.MOVING,true);
                    catch(PropertyVetoException pve)
                    StateModel.getInstance().incrementActiveThreadCount();
                    System.out.println("LocateSampleThread "+StateModel.getInstance().getActiveThreadCount());
                catch(InterruptedException ie)
    ...do activity here.
                synchronized(motionObject)
                    motionObject.notify();
                try
                    StateModel.getInstance().setActive(StateModel.MOVING,false);
                catch(PropertyVetoException pve)
                StateModel.getInstance().clearState(StateModel.MOVING);
                StateModel.getInstance().decrementActiveThreadCount();
                sendStageMotionEvent (new StageMotionEvent (this, false));
        public void moveAndWait () throws InterruptedException
            synchronized (motionObject)
                motionObject.notify();
                motionObject.wait();
        public void moveAndDontWait ()
            synchronized (motionObject)
                motionObject.notify();
        protected Object motionObject=null;in the controlling code
                                    try
                                        locateSampleThread.moveAndWait();
                                        //System.out.println("locateSampleThread notify/wait done");
                                        sleep(100);
                                    catch(InterruptedException ie)
                                    }Notice that the in moveAndWait the notify and wait ion the motionObject inside a synchronized is safe threading because the controlling code that calls moveAndWait will be waiting even before the thread's run(which is synchronized as well) starts going from being notified.

  • No Calrity on Multiple Inheritance Concept Of Java..!

    In SCJP Book by "karty serie " .
    In Java
    a subclass of class Object, (except of course class Object itself). In other words, every
    class you'll ever use or ever write will inherit from class Object. You'll always have
    an equals method, a clone method, notify, wait, and others, available to use.
    Whenever you create a class, you automatically inherit all of class Object's methods.
    A class cannot extend more than one class. That means one parent per class. A
    class can have multiple ancestors, however, since class B could extend class A, and
    class C could extend class B, and so on. So any given class might have multiple
    classes up its inheritance tree, but that's not the same as saying a class directly
    extends two classes.
    class PlayerPiece extends GameShape, Animatable { // NO!
    // more code
    If the above code is invalid, is it legal to write the code like ...
    class PlayerPiece extends GameShape, Object { // NO!
    // more code
    Thanks In Advance
    Kiran

    I think I can help straighten out what is confusing you.
    Let's say you have a class B that extends class A, and a class C that extends class B.
    Then class C implicitly extends class A, but java does not allow you to make that explicit.
    So, yes, in a way, class C does subtype both class A and B, but it only directly subclasses class B. The subtyping of class A is implicit.
    The following should demonstrate some patterns that should help clear things up:
    class A { } 
    // This automatically is a subclass of Object,
    // you don't need to specify that.
    // or
    class A extends Object { } 
    // This is legal, but not necessary, since a class
    // that doesn't extend anything else implicitly extends Object
    class B extends A { } 
    // This directly subclasses class A,
    // and implicitly subtypes Object
    // but
    class B extends A, Object { } 
    // This is NOT legal in java, and will not compile,
    // even though the previous code would
    // make class B a subtype of Object
    class C extends A { } 
    // Again, a direct subclass of A,
    // and indirect subclass of Object
    class D extends B, C { } 
    // This is NOT legal in java, and is what people
    // usually mean when they say that multiple
    // inheritance is prohibited.  In this case, you
    // are attempting to subclass two different
    // classes, where one is *not* a subtype of
    // another.  There is no work around to make
    // this happen in java, but you can use interfaces
    // and composition to get a similar effect with a
    // bit of glue code to hook things together.
    // For example:
    interface X {
      public void doX();
    class XImpl implements X {
      public void doX() {
        // do something
    interface Y {
      public void doY();
    class YImpl implements Y {
      public void doY() {
        // do something else
    class Z implements X, Y {
      private X x = new XImpl();
      private Y y = new YImpl();
      public void doX() {
        x.doX();
      public void doY() {
        y.doY();
    // This is basically what goes on behind the scenes
    // in languages like C++ that do support MI

  • IllegalMonitorStateException when closing streams

    Hi all,
    The following code throws an illegalMonitorStateException. Anyone know what I need to do?
    The documentatin says about an illegalMonitorStateException:
    Thrown to indicate that a thread has attempted to wait on an object's monitor or to notify other threads waiting on an object's monitor without owning the specified monitor.
    Do I need to notifyAll before closing?
         public void closeConnection () {
              try {
                   ins.close();    // InputStream
                   dins.close();   // DataInputStream
                   outs.close();   // OutputStream
                   douts.close();  // DataOutputStream
                   connection.close();
              catch (IOException ioException) {
                   displayMessage("IO Error", "Unable to close " +
                             "the connection (IOException: " +
                             ioException.getMessage() + ")");
              finally {
                   isGameCompleted = true;
                   notifyAll ();
                   bpMIDlet.destroyApp(true);
         }Thanks in advance.
    Maik

    What you need is:
    synchronized(this) {
          isGameCompleted = true;
          notifyAll ();
    }You should always surrond either a set and notify or a test and wait with synchronization on the object you are notifying/waiting on.

  • Design an asynchrounous application

    Hi all,
    I have to design an asynchronous application. There are many instances of my application Object which does some work and leaves the control of the Execution Thread waiting for some asynchronous event. One obvious way is to store the state which I was in before leaving the Execution Thread so that I can act accordingly when I get the events. This can be modelled on State Pattern, but this way I will have to create a new State every time I make an asynchronous call.
    One more requirement is these states can change very frequently, that is, this design must be extensible. Last but not the least, this is a Telecom Application, hence, performance is an absolute must.
    I could not think of some elegant way to do this. Please help, are there any design patterns describing such an intent?
    Thanx
    Fasih

    Thanx for the response...
    What's your 'application Object'?My application object is the call object and other state objects that store the state of the call that has come to the system... In simple terms it can be called a
    CallConnection object
    Or you could just use wait/notify.I cannot use a notify/wait mechanism because of the fact that the number of call objects active can run into thousands in the least.... as such to create so many threads is definitely a suicide....
    >
    This can be
    modelled on State Pattern, but this way I willhave
    to create a new State every time I make an
    asynchronous call.
    One more requirement is these states can changevery
    frequently, that is, this design must beextensible.
    Last but not the least, this is a Telecom
    Application, hence, performance is an absolutemust.
    Another thing you could do is add a hook method on
    your 'application Object' that's called whe the event
    is processed and store the state in your 'application
    Object'.I use a hook method... but that is the problem.... it becomes clumsy to mantain the code....
    What I am looking for is a clean / scalable and a high performance model that i can use
    thanx
    fasih

  • Thread ordering

    Hi all
    I have a little program that uses a barrier that makes a number of threads wait until a threshold has been reached.
    When this happens those threads are released and thereafter all threads pass.
    See below.
    public class BarrierDemo { 
         static int noOfThreads = 20;
           static int barrierSize = 10;
           static int interval = 500; 
           //static Threads[] threads;
           static Barrier barrier;
        public static void main(String args[]) {
           System.out.println("Number of threads = "+noOfThreads);
           System.out.println("Barrier Size = "+barrierSize);
           System.out.println("Interval = "+interval);
           barrier = new Barrier(barrierSize);
           for (int i=0 ; i<noOfThreads ; i++){
                new Threads(barrier, i).start();
                try{
                     Thread.sleep(interval);
                catch (java.lang.InterruptedException e){
                     System.out.println("sleep interupted (yawn :o).");
                     System.out.println(" Exception - "+e+".");                 
        private static class Threads extends Thread {
             Barrier barrier;
             int threadNo;         
             Threads(Barrier b, int i){
                  barrier = b;
                  threadNo = i;
             public void run(){
                  try{
                       System.out.println("Thread "+ threadNo +" is waiting at the barrier");
                       barrier.barrierControl();
                       System.out.println("Thread "+ threadNo +" passed the barrier");
                  catch (java.lang.InterruptedException e){
                       System.out.println(e);     
         private static class Barrier {
              private int count = 0;
              private int barrierSize;          
              Barrier(int i){
                   barrierSize = i;     
              synchronized void barrierControl() throws InterruptedException{
                   count++;
                   while (count <= barrierSize){
                        wait();
                   notifyAll();               
    } The output should be like this..
    Number of threads = 20
    Barrier Size = 10
    Interval = 500
    Thread 0 is waiting at the barrier
    Thread 1 is waiting at the barrier
    Thread 2 is waiting at the barrier
    Thread 3 is waiting at the barrier
    Thread 4 is waiting at the barrier
    Thread 5 is waiting at the barrier
    Thread 6 is waiting at the barrier
    Thread 7 is waiting at the barrier
    Thread 8 is waiting at the barrier
    Thread 9 is waiting at the barrier
    Thread 10 is waiting at the barrier
    Thread 0 passed the barrier
    Thread 1 passed the barrier
    Thread 2 passed the barrier
    Thread 3 passed the barrier
    Thread 4 passed the barrier
    Thread 5 passed the barrier
    Thread 6 passed the barrier
    Thread 7 passed the barrier
    Thread 8 passed the barrier
    Thread 9 passed the barrier
    Thread 10 passed the barrier
    Thread 11 is waiting at the barrier
    Thread 11 passed the barrier... etc.
    It usually does this. However, the ordering is not guaranteed. I thought about using an array so that I could find each specific thread in turn and notify() something like this...
    public class BarrierDemo { 
         static int noOfThreads = 20;
           static int barrierSize = 10;
           static int interval = 500; 
           static Threads[] threads;
           static Barrier barrier;
        public static void main(String args[]) {
           System.out.println("Number of threads = "+noOfThreads);
           System.out.println("Barrier Size = "+barrierSize);
           System.out.println("Interval = "+interval);
           threads = new Threads[noOfThreads];
           barrier = new Barrier(barrierSize);
           for (int i=0 ; i<noOfThreads ; i++){
                threads[i] = new Threads(barrier, i);
                threads.start();
         //new Threads(barrier, i).start();
         try{
              Thread.sleep(interval);
         catch (java.lang.InterruptedException e){
              System.out.println("sleep interupted (yawn :o).");
              System.out.println(" Exception - "+e+".");           
    //private static void notifications(int t) {
    //     threads[t].notify();
    private static class Threads extends Thread {
         Barrier barrier;
         int threadNo;      
         Threads(Barrier b, int i){
              barrier = b;
              threadNo = i;
         public void run(){
              try{
                   System.out.println("Thread "+ threadNo +" is waiting at the barrier");
                   barrier.barrierControl(threadNo);
                   System.out.println("Thread "+ threadNo +" passed the barrier");
              catch (java.lang.InterruptedException e){
                   System.out.println(e);     
         private static class Barrier {
              private int count = 0;
              private int barrierSize;          
              Barrier(int i){
                   barrierSize = i;     
              synchronized void barrierControl(int threadID) throws InterruptedException{//passports please :o)
                   count++;
                   while (count <= barrierSize){
                        wait();
                   for (int i=0 ; i<noOfThreads ; i++){
                        threads[i].notify();
                        //BarrierDemo.notifications(i);
                   //notifyAll();
    but that doesn't work.
    The output is then like this;
    ... Thread 9 is waiting at the barrier
    Thread 10 is waiting at the barrier
    Exception in thread "Thread-10" java.lang.IllegalMonitorStateException: current
    thread not owner... etc.
    I also thought about changing their priorities but from what I have read this does not guarantee the order either.
    Can anyone advise me how I can strictly enforce the order ?
    Cheers

    Hi
    I found out later that the task was badly specified. Whereas I the output we were asked to acheive showed each thread coming through exactly in order, this was not required. All that was required was that those numbered up to the barrier size wait and then the first lot go through (up to and including the thread number equal to the barrierSize) then followed by all others (however many follow).
    I was asked to look again at my solution using wait and notify.
    My prog actually did what I was asked to do but I didn't realize that strict order throughout wasn't necessary!
    Anyhow the Barrier class code ended up something like this.
         private static class Barrier {
              private int barrierSize;
              Barrier(int i){
                   barrierSize = i;     
              synchronized void barrierControl(int t) throws InterruptedException{
                   if(t <= barrierSize){
                        wait();
                        notify();
                   if(t == barrierSize +1){
                        notify();
                        wait();
    Which was acceptable (not sure if I eventually used notifyAll( ) though). I will have the oportunity to discuss over the phone so I can get a better idea of what I should have done.
    NotifyAll( ) was expected, to tell the rest to go through but I used notify() ( I was still trying to keep the exact order one-by-one).
    Thanks for your interest.
    :o)

Maybe you are looking for

  • How to create a selection field in Infopackage

    Hello  Experts, Greetings. My Requirement is to have a infopackage to dynamically accept the selection field values Now I Understand the we can only populate single ragne of values VIA ABAP Routine. Eg: 0Plant : 1 to 99999999999 But now my requiremen

  • Stick with Tiger!

    I updated 2 weeks ago to a genuine Leopard OS from the Apple store. The Docks now disappeared - wont come back on Windows wont minimise. System keeps 'sticking' - the whole thing pauses now and again. All the Fkeys are shot Spaces has been disabled a

  • HT2963 Warning: SUID file ------will not be repaired.

    Hi:   When trouble shooting some difficulties in a game I was directed to run    Disk Utility Program ---Disk Utilities Repair Disk Permissions I ran the program and got this Warning. Warning: SUID file "System/Library/CoreServices/RemoteManagement/A

  • You can't read the text. It is over laying each other.

    When I open some web pages the text is over laid each other. Like two rows over laying each other. I am very new to Mac so I have no idea how to fix it. Please help....Thx

  • Detecting multiple key presses

    Using the code below I am trying to detect keypresses for a java applet which involves holding down of several keys at once. I have 2 problems, probably related. Firstly I can only detect 3-4 simultaneous keys being held down and secondly the keyPres