Java callback mechanism

How do we implement "callback" mechanism in java. ? can any on eexplain me with an example?

yo_man123 wrote:
when somethingHappened becomes true?When your code sets it to be true. This event notification idiom is a way for one piece of code to notify another piece of code that something has happened. I think you're over-thinking it. It's quite common for newbs to think there's some magic going on inside the JVM that somehow detects when an event should be raised. There isn't. You do it. You detect when the change has happened, and notify other objects. It'll be easier to explain if you have a concrete need for doing it. If you're just looking at the exercise and hoping it'll stick, you'll hit, well, the problem you've hit - not having an event to relate it to in your head.

Similar Messages

  • App crash when using JAVA callbacks from native threads in solaris

    Hi all,
    Sorry for putting the thread here. I did use the native methods forum, I wasnt lucky. I Hope more people would look into this forum, which brings me here.
    I have a solaris application which crashes when I try to callback the JAVA methods and variables from the native code. The description of the problem is below
    Written a native library, the library is multithreaded (i.e) I create a thread using pthread_create() in the native code which performs the operation of calling a JAVA method from the native code. The routine of calling the JAVA method works perfectly elsewhere outside the new thread.
    There are two scenarios I've tested it in
    1. I created a thread (say X) from the main thread (say Y) and made the y to wait until the X is complete using the pthread_join(). The JAVA callbacks works fine when called from Y but the app crashes if done from X.
    2. Did not make the Y to wait until the X is complete, hoping that both will run paralelly and even the the App crashes.
    And to be precise the Y is the thread where the native method is called from JAVA.
    I have tested for any memory leaks or stack corruption by removing the JAVA callbacks and bulding a executable and using purify, the report doesnot hint any such occurances.
    The linker options used for building the shared library is as follows
    ${GPP} ${INC} -G ${LIB} -mt -g -lCstd -lCrun -lpthread ${OBJS} -o <lib-name>
    I wonder if we can create threads in the native code when using JAVA callbacks and even if we can whether it would be appropiate to use the callbacks with in the threads
    Looking forward for any help.
    Regards,
    Vamsi

    Guys... can't any one help me with this problem :(

  • Oracle Callback Mechanism

    I want to know how many ways Oracles provides Callback mechanism on process level ( e.g. c application ).
    currently I know:
    (1)Advanced Queuing
    (2)Database Change Notification
    (3)OCI API callback.
    I'm looking for a fast(real-time) callback mechanism (faster than AQ & DCN) and trigging events happen on Stored Procedure level or Table level(not OCI API level).
    Is there any?( we are using Oracle 10g, your help is much appreciated)

    Oracle is not a real-time database. Nor does Oracle run on any real-time operating systems as far as I know.
    And you will need both for real-time processing. A real-time database and a real-time o/s.
    Which begs the question - what are you trying to achieve and why? Real-time processing is not typical, especially in the RDBMS environment that by its very nature of concurrency controls, ACID properties and so on, cannot be real-time.

  • Callback mechanism is not working in Javascript

    JDK versions: Problem occurs in JRE1.4.2 and JRE1.5 (JRE142_05, 5.0 beta), but NOT JRE1.3.1.
    OS: WIndows
    Here is the problem Scenario
    1. A Webpage ( GOM - Javascript ) is running
    2. Clicking on a button in the above webpage will load an applet ( enc3 )
    3. Once we are done with the applet, click on return button to go back to GOM
    4. To return to GOM, function performMiniflowReturnWithMessage in the java file is called which in turn calls "this.getAppletContext().showDocument(new URL(miniFlowClosePage.toString()),"_top");".
    Subsequently function closeMiniflowWindow() is called in the HTML page which in turn calls sendREsultsToGOM.
    Here the call to ""opener."+returnStatusMethodName+"(status, msg, data);";" is throwing a javascript error in Sun plugin.
    Exact text of error message:
    The exact error message is ( JavaScript Error: http://nc3ft3a.ugd.att.com/enc3home/closeminiflowapplet.html??Callback=NC3_alertOnError&Status=-1&Msg=Neither E2EPVC_ODBIDS or ROUTER_ODBID Params was not sent to VPN applet.&, line 44: opener.NC3_alertOnError is not a function )
    Here are our findings :
    1. I could notice that "getAppletContext().showDocument" is one java api that customer is using and this is being called before application encounters problem reported that is the javascript error
    2. showDocument API's functionality is that it requests that the browser or applet viewer show the Web page indicated by the url argument. This API has 2 parameters one is URL and other is the TARGET.
    Target can be any one these
    a. "_self" show in the current frame
    b. "_parent"show in the parent frame
    c. "_top" show in the topmost frame
    d. "_blank" show in a new unnamed top-level windownameshow in a new top-level window named name
    3. In the customer's application, for this API showdocument, URL argument passed is "enc3home/closeminiflowapplet.html?" and _top is passed as Target argument. Hence, the expected behaviour is that topmost frame of this URL that is GOM should be shown instead the above javascript error is thrown. The probable cause could be that instead of getting the link to GOM ( topmost window of enc3 ),  application is getting link to enc3 itself.
    4. Actually this.getAppletContext() as used in the application along with showDocument sun.plugin.viewer.context.NetscapeAppletContext. Therefore NetscapeAppletContext.showDocument is called within the application.
    5. NetscapeAppletContext extends DefaultPluginAppletContext and the showDocument method of this class is called. This function inturn calls doShowDocument. I suspect these functions and this needs to be investigated.
    Also please note that the classes NetscapeAppletContext and DefaultPluginAppletContext are not there in 131 and customer says that problem is not there in 131. Also, the this.getAppletContext will return sun.plugin.navig.win32.AppletPluginContext.
    Application source code is available.

    in this part:
    if(document.LForm.uname.value==null || document.LForm.upassword.value==null)should be:
    if(document.LForm.uname.value=="" || document.LForm.upassword.value=="")or
    if(document.LForm.uname.value.length==0 || document.LForm.upassword.value.length==0)

  • Java callback from bpel

    As i read somewhere the type of the handle.getResult type is DOM Element...
    it gives returns java.lang.ClassCastException
    the code is the following.
    java.util.Properties props = new java.util.Properties();
    props.setProperty("orabpel.platform", "oc4j_10g");
    props.setProperty("java.naming.factory.initial", "com.evermind.server.rmi.RMIInitialContextFactory");
    props.setProperty("java.naming.provider.url", "ormi://localhost:23791/orabpel");
    props.setProperty("java.naming.security.principal", "admin");
    props.setProperty("java.naming.security.credentials", "welcome");
    com.oracle.bpel.client.Locator locator = new Locator("default","bpel",props);
    IInstanceHandle handle = locator.lookupInstance("2");
    Object res = handle.getResult();
    org.w3c.dom.Element element = (org.w3c.dom.Element)res;
    any clues as to how to get the result from an async process?

    Hello globo,
    if you have a synchronous process you simple use
    NormalizedMessage nmRet = deliveryService.request(processName, processMethod, normalizedMessage);
    nmRet.getPayload();
    And here you have the payload of your return.
    For callbacks and values from an asynchronous process have a look at clemens' blog:
    http://clemensblog.blogspot.com/2006/04/bpel-implementing-async-callback-with.html
    Greets Jens

  • Java callback from C

    I'm trying to call Java class method from C code (via JNI), but Java VM dies with
    # An unexpected error has been detected by HotSpot Virtual Machine:
    #  EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x6d6c79dd, pid=128, tid=2192
    # Java VM: Java HotSpot(TM) Client VM (1.5.0_11-b03 mixed mode)
    # Problematic frame:
    # V  [jvm.dll+0x879dd]
    # An error report file with more information is saved as hs_err_pid128.log
    # If you would like to submit a bug report, please visit:
    #   http://java.sun.com/webapps/bugreport/crash.jsp
    Hello world!
    Hello world, from Java to C!This is Java code:
    Hello.java
    class Hello
         public native void sayHello();
         public native void sayHello(String hello);
         public native void sayHello(Callback callback);
         static
              try
                   System.loadLibrary("hello");
              catch(Exception e)
                   System.out.println("exception " + e.getMessage());
         public static void main(String[] args)
              Hello h = new Hello();
              h.sayHello ();
              h.sayHello("Hello world, from Java to C!");
              Callback callback = new Callback();
              h.sayHello(callback);
    }Callback.java
    public class Callback
         public void sayHello(int num)
              for(int i=0; i<num; i++)
                   System.out.println("Hello world, from C to Java!");
    }This is C code:
    Hello.c
    #include <mingw/_mingw.h> //because there are some types needed for JNI
    #include <jni.h>
    #include "Hello.h"
    #include <stdio.h>
    JNIEXPORT void JNICALL Java_Hello_sayHello__
      (JNIEnv *env, jobject obj)
         printf("Hello world!\n");
         return;
    JNIEXPORT void JNICALL Java_Hello_sayHello__Ljava_lang_String_2
      (JNIEnv *env, jobject obj, jstring hello)
         const char *str = (*env)->GetStringUTFChars(env, hello, 0);
         printf("%s", str);
         (*env)->ReleaseStringUTFChars(env, hello, str);
         return;
    JNIEXPORT void JNICALL Java_Hello_sayHello__LCallback_2
      (JNIEnv *env, jobject obj, jobject call)
         jclass clazz = (*env)->GetObjectClass(env, call);
         jmethodID id = (*env)->GetMethodID(env, clazz, "sayHello", "(I)V");
         if(id == NULL)
              //(*env)->ExceptionDescribe(env);
              (*env)->ExceptionClear(env);
              printf("Method not found!\n");
    }C if linked with
    gcc -mno-cygwin -Wl,--add-stdcall-alias,--kill-at -shared -Wl,--output-def=Hello.def -o"hello.dll"  ./Hello.oand 'def' file is:
    EXPORTS
    Java_Hello_sayHello__
    Java_Hello_sayHello__Ljava_lang_String_2
    Java_Hello_sayHello__LCallback_2I can't see what am I doing wrong, but I'm sure thats something plain that I'm missing. Code is compiled with latest Cygwin in Eclipse 3.2.2 under WinXP OS. It is runned under jre1.5.0_11.
    Any help is appreciated. Thanks.

    Now I commented two calls for printing on screen in C code, and left just callback call, and same error is still there:
    # An unexpected error has been detected by HotSpot Virtual Machine:
    #  EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x6d6c79dd, pid=3656, tid=3660
    # Java VM: Java HotSpot(TM) Client VM (1.5.0_11-b03 mixed mode)
    # Problematic frame:
    # V  [jvm.dll+0x879dd]
    # An error report file with more information is saved as hs_err_pid3656.log
    # If you would like to submit a bug report, please visit:
    #   http://java.sun.com/webapps/bugreport/crash.jsp
    #Can anyone tell me what does this mean (or how to fix my code)?
    Thank you for your reply.

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

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

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

  • Thread Pool Callback Mechanism

    I am using java.util.concurrent.ExecutorService to create a thread pool. I need a way to inform the user of the progress of the threads in the pool.
    Does anyone have any ideas of how to do this?

    I am using java.util.concurrent.ExecutorService to
    create a thread pool. I need a way to inform the user
    of the progress of the threads in the pool.
    Does anyone have any ideas of how to do this?Hand the Executor instances of SwingWorker, which implements RunnableFuture. SwingWorker also has a progress() method which can provide progress information.

  • Java Extensions Mechanism is not working

    I'm using Java SE SDK 1.6 update 3 on Windows XP SP2.
    I have a Java application which uses jar files from other providers. Copied those jar files to %JAVA_HOME%\jre\lib\ext directory to make these jar files search ables.
    Also JAVA_HOME environment variable is set to the full path of Java SE SDK.
    When try to run Java application an exception is thrown indicating that classes are not found.
    What could be wrong?
    Thanks in advance for your help.
    Regards.

    REFTY5_ wrote:
    After that I have enabled java in mozila and restarted the firebox.I've been having problems with my firebox, too. Nevertheless, this is a forum about Java programming. If you need support for running a third-party applet in a particular browser, I strongly recommend contacting the applet distributor or website support directly.
    ~

  • Java "Endorsed" Mechanism not working?

    Hello,
    I came across a very strange issue earlier this week. I was getting a "NoSuchMethodError" from somewhere in my code. Googling the problem revealed that I was supposed to "endorse" some certain jar files (jaxb-api.jar and jaxws-api.jar). Here is where my problem started.
    I added the following option to java when running my code (my jar file(s) ):
    -Djava.endorsed.dirs="/path/endorsed"
    (For the record: YES, the jar files are in that directory. I've tried all sorts of different configurations in terms of this endorsed dirs option, the classpath, and copying/moving files around. I have thus far been unable to get it to work.)
    My code is run from C++ which looks at a conf file to see what options to pass java. This is a potential weakness (an extra "moving part"), but I'm pretty sure these options are concatenated correctly because when I put in the "-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=1044" option, it correctly suspends execution until I attach a debugger. Clearly this is a pretty lazy test, but like I said it's passing the option. Unless java is peculiar about the order of these commandline options, I don't see a problem here.
    So, by this point I was pulling my hair out trying to figure this out. I am extremely averse to shoving these jars into the jre/lib/endorsed directory, but I finally tried that (I actually didn't think there was any difference, but it was a last-ditch effort). To my surprise, my code ran fine without the "NoSuchMethodError." So, for now we have this jar file in the "official" jre endorsed directory, but ideally I would be able to figure out this java.endorsed.dirs option so we didn't have to do that (it just seems so dirty - and global, which I especially don't like).
    Getting the full java command is a little trick, but I can provide that if necessary. From what I can see in the code it's being constructed as:
    java <JAVA_OPTIONS> -jar "<MY_JAR>" "<MY_MAIN_ARGS>"
    where:
    <JAVA_OPTIONS> comes from this conf file (which I was setting as '-Djava.endorsed.dirs="/path/endorsed" ')
    <MY_JAR> is the full path to my "main" jar file which obviously references a bunch of other jars, including these jaxws-api and jaxb-api jars.
    <MY_MAIN_ARGS> is the list of arguments passed into the main function which tells "<MY_JAR>" what to do.
    P.S.> I also noticed that if I shove these files into the jre/lib/endorsed directory and I still specify the -Djava.endorsed.dirs option, it acts as though the files are not endorsed ("NoSuchMethodError"). As soon as I take the option out, it starts working (no error). I don't know if this is relevant information besides the fact that it seems the -Djava.endorsed.dirs option is actually being passed, even though it's not doing what I expect (as in, it's affecting the execution in some way so it must be making a difference in the call somehow).
    So, what gives? Why does -Djava.endorsed.dirs not work?

    Hi Gayatri,
    There are a lot of reasons as to why the java stack could be down. Try bouncing the J2EE stack again. ( restart), and see if it works
    All the best!
    cheers,
    Prashanth
    P.S Please mark helpful answers

  • Use Java Logging mechanism

    We have a requirement to log application errors in a local log file in the form of key/value pairs (from a property object) after every transaction, append to the previous transaction and generate one log file for each day.
    Log file example,
    currentTime=xxxx
    message=xxxxx
    userId=xxxx
    etc.
    What would be the best way to do it ? Can I take advantage of the Java Logging API, like file handler , although it does not do exactly what I wanted ?

    Thanks for the reply. But the company standard does
    not allow open source package like log4j.Then the company standard is completely nuts... but they're like that aren't they... I'd still get a copy of the log4j source from the apache site, to use a working example of how to do it well... then maybe write a simplified "write behind" logging service based on it... a single format "log4j-lite"
    Have fun with it.
    Keith.

  • Java Extensions Mechanism is not working on Windows Vista

    I have installed JDK 1.6 Update 2 on Windows Vista Ultimate. Additional jar files sucha as JDBC drivers, etc were copied to $JAVA_HOME/jre/lib/ext directory to make these packages visible without specify their locations in classpath environment variable.
    This mechanism works fine on Linux and Windows XP, but in the case of Win Vista, classes aren't found. When try to run a class that has references to these packages, an exception is thrown indicating that those classes don't exist or weren't found.
    I don't know if I'm missing something or if I'm doing anything wrong. If that's true, please let me know to fix it ASAP.
    Thanks in advance for your help.
    Regards.

    Hi, Have you tried going into Device Manager and doing a scan for hardware changes through the Action menu? This should find your microphone again and fix the issue
    HP Pavilion DV9730CA - AMD Turion 64 X2 TL-64 2200MHz, 2GB (2x1024MB) SODIMM RAM, 320GB (2x160GB) Seagate 5400rpm HDD's, nVidia GeForce 8400 GS Graphics, Broadcom ABG Draft N Wireless, HD DVD SuperMulti DL DVD+RW, 4 USB 2.0, S Video, VGA, HDMI, Firewire, 5 in 1 card reader, RJ-45, RJ-11, Expansion Port 3, Expresscard 34/52.

  • Java callback / Calling object identification

    This runs on very similar lines to the topic by rishab, "Knowing the identity of the calling application."
    Basically, when an arbitrary method is called on an arbitrary object, I need to be able to get a reference to the calling object, for authorization and callback purposes.
    Details...
    * All objects that require this will be subclasses of a common class, so this functionality can be implemented in that class.
    * These objects should be pluggable - created by anyone, compiled and added on the fly, therefore implementation of this should not be required in subclasses.
    * A reference to the calling object is required, without the object being passed, so such authorization cannot be compromised by providing proxy accessors or passing bogus objects.
    * Reflection to call a method from a base class and force passing the calling method appears to be infeasible, since exact method-type matching appears to prevent polymorphism in reflection.
    SecurityManager.getClassContext() is halfway there, in that is exposes what kind of object called the method, but for complete authorization and callback it is necessary to know which instance called the method.
    If anyone has any information that might get me on the right track, I would be most grateful.
    Regards,
    -Troy

    As you mentioned, this is very similar to another topic posted. To obtain an object reference to a caller WITHOUT sending an object reference is "de facto" problematic. Any solution will require a compromise to the design terms you described.
    I think there's no pratical way to get around passing an object reference as a parameter. However, you could create an interface implemented by all calling classes that would contain a specific call-back method that would authorize the client before allowing the method to proceed.
    This would require some sort of basic shared secret or handshake to be returned by the client's implementation of the interface method. Otherwise, you could implant the correct response into the client's superclass and declare it final. That way, when the shared object invokes the superclass method on the client, it could verify the instance and simply return a boolean.
    public class SharedObject {
    myMethod(Object O) {
    ...check if O implements myInterface...
    ...call ((myInterface)O).checkMyClient()
    ...if I'm satified, continue to interact with O
    ...else do nothing
    }

  • "DEADLOCK" when showing dialog from RMI-callback.

    Hi!
    Today is the 10th day (full time) that I've been searching for a solution in Java Forums and Internet, but I couldn't find anything that helps me. Help is extremely appreciated, otherwise I'll go crazy! :-)
    The problem is that RMI-callback thread "somehow blocks" the Event Dispatch Thread.
    I want to do following:
    1) I push the button in the client (btDoSomething)
    (MOUSE_RELEASED,(39,14),button=1,modifiers=Button1,clickCount=1 is automatically pushed onto EventQueue)
    2) btDoSomethingActionPerformed is invoked
    3) inside of it I make a call to RMI-server (server.doSomething())
    4) from this server method I invoke RMI-callback back to the client (client.askUser())
    5) in the callback I want to display a question to the user (JOptionPane.showConfirmDialog)
    6) user should answers the question
    7) callback returns to server
    8) client call to the server returns
    9) btDoSomethingActionPerformed returns and everybody is happy :-)
    This works normally in normal Client, that means, while a button is pushed, you can show Dialogs, but with RMI callback I get problems.
    I just made a small client-server sample to simulate real project. What I want to achieve is that client invokes server method, server method does something, but if server method doesn't have enough information to make the decision it needs to do call back to the client and wait for input, so the user gets an JOptionPane.
    Here is my callback method:
        /** this is the remote callback method, which is invoked from the sevrer */
        public synchronized String askUser() throws java.rmi.RemoteException {
            System.out.println("askUser() thread group: " + Thread.currentThread().getThreadGroup());
            System.out.println("callback started...");
            try {
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        System.out.println("My event started...");
                        JOptionPane.showConfirmDialog(parentFrame, "Are you OK?", "Question", JOptionPane.YES_NO_OPTION);
                        System.out.println("My event finished.");
            }catch (Exception e) {
                e.printStackTrace();
            try {
                Thread.currentThread().sleep(10000);
            }catch (Exception e) {
                e.printStackTrace();
            System.out.println("callback finished.");
            return "Yo!"; // just return anything
        }Here in this sample I let the callback thread sleep for 10 seconds, but in real project I let it sleep infinitely and I want to wake it up after the user has answered JOptionPane. But I have the DEADLOCK, because event queue is waiting for callback to finish and doesn't schedule the "showing dialog" event which contains the command for waking up the callback thread.
    I looked very precisely when the event queue starts again to process events: it is precisely then when btDoSomethingActionPerformed is finished.
    When I'm not accessing GUI inside of the callback, this callback mechanism works perfectly, but as soon as I want to show the dialog from inside of the RMI-callback method, the "AWT Event Dispatch Queue" is somehow frozen until RMI-callback thread is finished (and in turn btDoSomethingActionPerformed terminates) . I cannot explain this weird behaviour!!!
    If I don't use SwingUtilities.invokeLater (I know this shoudn't be done outside of Event Dispatch Thread), but access the GUI directy, my JOptionPane is shown, but is not painted (it is blank gray) until callback thread returns.
    Why showing (or painting) of dialog is not done until btDoSomethingActionPerformed is finished?
    I also tried to spawn a new Thread inside of main RMI-callback thread, but nothing changed.
    I also tried the workaround from some older posting to use myInvokeLater:
        private final static ThreadGroup _applicationThreadGroup = Thread.currentThread().getThreadGroup();
        public void myInvokeLater(final Runnable code) {
            (new Thread(_applicationThreadGroup, new Runnable() {
                public void run() { SwingUtilities.invokeLater(code); }
            ).start();
        }but this didn't help either.
    Then I tried to spawn a new Thread directly from the Client's constructor, so that I'm sure that it belongs to the main appplication thread group. I even started that thread there in the constructor and made it wait for the callback. When callback came in, it would wake up that sleeping thread which should then show the dialog. But this did't help either.
    Now I think that it is IMPOSSIBLE to solve this problem this way.
    Spawning a new Process could work I think, but I'm not really sure if I want do to that.
    I know I could make a solution where server method is invoked and if some information is missing I can raise custom exception, provide the input on client side and call the same server mathod again with this additional data, but for that I need to change server RMI interfaces, etc... to fit in this concept. I thought callback would much easier, but after almost 10 days of trying the callback...I almost regreted it :-(
    Is anyone able to help?
    Thank you very much!
    Please scroll down for the complete sample (with build and run batch files), in case someone wants to try it. Or for the time being for your convenience you can download the whole sample from
    http://www.onlineloop.com/~tornado/download/rmi_callback_blocks_gui.zip
    ######### BEGIN CODE ####################################
    package callbackdialog;
    public interface ICallback extends java.rmi.Remote {
        public String askUser() throws java.rmi.RemoteException;
    package callbackdialog;
    public interface IServer extends java.rmi.Remote {
        public void doSomething() throws java.rmi.RemoteException;
    package callbackdialog;
    import java.rmi.Naming;
    public class Server {
        public Server() {
            try {
                IServer s = new ServerImpl();
                Naming.rebind("rmi://localhost:1099/ServerService", s);
            } catch (Exception e) {
                System.out.println("Trouble: " + e);
        public static void main(String args[]) {
            new Server();
    package callbackdialog;
    import java.rmi.Naming;
    public class ServerImpl extends java.rmi.server.UnicastRemoteObject implements IServer {
        // Implementations must have an explicit constructor
        // in order to declare the RemoteException exception
        public ServerImpl() throws java.rmi.RemoteException {
            super();
        public void doSomething() throws java.rmi.RemoteException {
            System.out.println("doSomething started...");
            try {
                // ask the client for the "missing" value via RMI callback
                ICallback client = (ICallback)Naming.lookup("rmi://localhost/ICallback");
                String clientValue = client.askUser();
                System.out.println("Got value from callback: " + clientValue);
            }catch (Exception e) {
                e.printStackTrace();
            System.out.println("doSomething finished.");
    package callbackdialog;
    import java.rmi.server.RemoteStub;
    import java.rmi.server.UnicastRemoteObject;
    import java.rmi.registry.Registry;
    import java.rmi.registry.LocateRegistry;
    import java.rmi.Naming;
    import javax.swing.JOptionPane;
    import javax.swing.SwingUtilities;
    import javax.swing.JFrame;
    public class Client extends javax.swing.JFrame implements ICallback {
        private final JFrame parentFrame = this;
        private Registry mRegistry = null;
        private RemoteStub remoteStub = null;
        private IServer server = null;
        private final static ThreadGroup _applicationThreadGroup = Thread.currentThread().getThreadGroup();
        /** Creates new form Client */
        public Client() {
            initComponents();
            System.out.println("Client constructor thread group: " + Thread.currentThread().getThreadGroup());
            try {
                server = (IServer)Naming.lookup("rmi://localhost/ServerService");
                // register client to the registry, so the server can invoke callback on it
                mRegistry = LocateRegistry.getRegistry("localhost", 1099);
                remoteStub = (RemoteStub)UnicastRemoteObject.exportObject((ICallback)this);
                Registry mRegistry = LocateRegistry.getRegistry("localhost", 1099);
                mRegistry.bind("ICallback", remoteStub);
            }catch (java.rmi.AlreadyBoundException e) {
                try {
                    mRegistry.unbind("ICallback");
                    mRegistry.bind("ICallback", remoteStub);
                }catch (Exception ex) {
                    // ignore it
            }catch (Exception e) {
                e.printStackTrace();
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        private void initComponents() {
            java.awt.GridBagConstraints gridBagConstraints;
            secondTestPanel = new javax.swing.JPanel();
            btDoSomething = new javax.swing.JButton();
            getContentPane().setLayout(new java.awt.GridBagLayout());
            setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
            setTitle("RMI-Callback-GUI-problem sample");
            addWindowListener(new java.awt.event.WindowAdapter() {
                public void windowClosing(java.awt.event.WindowEvent evt) {
                    formWindowClosing(evt);
            secondTestPanel.setLayout(new java.awt.GridBagLayout());
            btDoSomething.setText("show dialog");
            btDoSomething.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    btDoSomethingActionPerformed(evt);
            gridBagConstraints = new java.awt.GridBagConstraints();
            gridBagConstraints.gridx = 0;
            gridBagConstraints.gridy = 3;
            gridBagConstraints.insets = new java.awt.Insets(10, 0, 0, 0);
            secondTestPanel.add(btDoSomething, gridBagConstraints);
            gridBagConstraints = new java.awt.GridBagConstraints();
            gridBagConstraints.gridx = 0;
            gridBagConstraints.gridy = 1;
            gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
            gridBagConstraints.weightx = 1.0;
            gridBagConstraints.weighty = 1.0;
            getContentPane().add(secondTestPanel, gridBagConstraints);
            pack();
        private void btDoSomethingActionPerformed(java.awt.event.ActionEvent evt) {                                             
            System.out.println(java.awt.EventQueue.getCurrentEvent().paramString());
            try {
                server.doSomething(); // invoke server RMI method, which will do the client RMI-Callback
                                      // in order to show the dialog
            }catch (Exception e) {
                e.printStackTrace();
        private void formWindowClosing(java.awt.event.WindowEvent evt) {                                  
            try {
                mRegistry.unbind("ICallback");
            }catch (Exception e) {
                e.printStackTrace();
            setVisible(false);
            dispose();
            System.exit(0);
        /** this is the remote callback method, which is invoked from the sevrer */
        public synchronized String askUser() throws java.rmi.RemoteException {
            System.out.println("askUser() thread group: " + Thread.currentThread().getThreadGroup());
            System.out.println("callback started...");
            try {
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        System.out.println("My event started...");
                        JOptionPane.showConfirmDialog(parentFrame, "Are you OK?", "Question", JOptionPane.YES_NO_OPTION);
                        System.out.println("My event finished.");
            }catch (Exception e) {
                e.printStackTrace();
            try {
                Thread.currentThread().sleep(10000);
            }catch (Exception e) {
                e.printStackTrace();
            System.out.println("callback finished.");
            return "Yo!"; // just return anything
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    Client client = new Client();
                    client.setSize(500,300);
                    client.setVisible(true);
        // Variables declaration - do not modify
        private javax.swing.JButton btDoSomething;
        private javax.swing.JPanel secondTestPanel;
        // End of variables declaration
    1_build.bat
    javac -cp . -d . *.java
    rmic callbackdialog.ServerImpl
    rmic callbackdialog.Client
    pause
    2_RunRmiRegistry.bat
    rmiregistry
    pause
    3_RunServer.bat
    rem java -classpath .\ Server
    java callbackdialog.Server
    pause
    4_RunClient.bat
    java callbackdialog.Client
    pause
    ######### END CODE ####################################

    I can understand that only partially, because SwingUtilities.invokeLater puts(redirects) my runnable object directly into AWT thread. The only conclusion I can draw from all things that I have tried until now , is that SwingUtilities.invokeLater(<showing the dialog>) invoked from a RMI thread somehow have lower "priority" than events coming directly from the AWT-thread and therefore it is held back until normal awt event completes (in this case BUTTON_RELEASED).
    But what I don't understand is the fact that the dialog is not shown even If I create and start a new thread from the client's constructor. This thread has nothing to do with RMI as it is in the main thread group:
        private BlockingObject dialogBlocker = new BlockingObject();
        private BlockingObject blocker = new BlockingObject();
        public Client() {
            initComponents();
            (new Thread() {
                public void run() {
                    try {
                        dialogBlocker.sleep(0);
                        System.out.println("My event started...");
                        JOptionPane.showConfirmDialog(parentFrame, "Are you OK?", "Question", JOptionPane.YES_NO_OPTION);
                        blocker.wake();
                        System.out.println("My event finished.");
                    }catch (Exception e) {
                        e.printStackTrace();
            }).start();
            ...Callback is then only used to wake up this thread which should display the dialog:
        public Object askUser() throws java.rmi.RemoteException {
            System.out.println("callback started...");
            dialogBlocker.wake();
            blocker.sleep(0);
            System.out.println("callback finished.");
            return userChoice; // return anything I don't care for now
    class BlockingObject {
        public void sleep(long timeout) {
            synchronized(this){
                try {
                    wait(timeout);
                }catch (InterruptedException e) {}
        public void wake() {
            synchronized(this){
                notifyAll();
        }In this case the dialog is shown, but it is NOT painted, so I have deadlock again. Why it is not painted?!?
    Haven't I uncouple it from RMI-Thread?
    But perhaps I'm looking at the wrong side of the whole thing.
    If I invoke server.doSomething (as ejp proposed) in a separate thread, then everything is fine (except that I cannot use this solution in my project :-( ).
    It seems that the whole problem is NOT AT ALL related to callback itself, but rather to the fact that if client invokes remote call, even dialogs can't be shown until the rmi call returns to the client.
    Thank you, Drindilica

  • After AttachCurrentThread: Calling back to Java method crashes JVM

    Hi,
    so I managed to get my multithreaded native code being invoked from a Java program.
    However, as soon as I try to invoke a Java callback from native code not running in the main thread, the program segfaults. Here's my code:
    // in the main thread, I store a pointer to the JVM that invokes this code
        if (env->GetJavaVM(&jvm) < 0) {
            std::cerr << "JNI ERROR: Failed getting reference to Java VM" << std::endl;
            return;
        assert (jvm != NULL);
    // in some other concurrently running (native) thread:
        JNIEnv *env;
        if (jvm->AttachCurrentThread((void**)&env, NULL) != JNI_OK) {
            std::cerr << "ERROR: Could not attach event thread to JVM" << std::endl;
            return;
        assert (env != NULL);
        assert (connector != NULL);
        assert (focusEventCallback != NULL);
        // the following line segfaults
        env->CallVoidMethod(connector, focusEventCallback);"connector" is a POJO, focusEventCallback the jmethodID referencing the Java callback.
    Am I missing something?
    Thanks in advance,
    Matthias

    jschell wrote:
    What do you mean by that? I get this reference in the main thread in JNI_OnLoad and I use it in another thread. So I use it across thread boundaries. Is that what you mean?Generally not a good idea.So what do you suggest?
    Getting that reference inside the thread where I use it didn't work, because the class lookup failed (ClassNotFoundException).Which means your code was wrong, not that it wouldn't work.So, what in particular was wrong about my code? Here is the section of the code that did not work, because the class lookup failed:
        JNIEnv *env = NULL;
        // "import" the native user level thread as a Java thread in the JVM
        if (jvm->AttachCurrentThread((void**)&env, NULL) != JNI_OK) {
            std::cerr << "JNI ERROR: Could not attach X11 event thread to JVM" << std::endl;
            return;
        jclass connectorClass = env->FindClass("de/dfki/km/mydesk/nativeInterfaces/linux/NetWmConnector");
        if (env->ExceptionOccurred()) {
            env->ExceptionDescribe(); // will output ClassNotFoundException
        }The same code works inside JNI_OnLoad.
    Well, an assertion is supposed to do that: Terminate the program if there is a condition that would stop the program from operating properly. The crashes I was talking about are segmentation faults. A failing assertion is not a crash, it will just terminate the program with an "assertion failed" message.You are not writing a C/C++ app. You are running some code in a shared library that is run from a VM.
    Very different.
    I haven't tried it but I am rather certain that if you cause an assertion failure that you are going to see a crash. So far as I know the only exit mechanism that doesn't cause the VM to crash explicitly is a system exit call. And that probably shouldn't be used either (not normally.)Well, as far as I know, assert() sends an abort signal and terminates the process (which is the VM in this case). I probably overused assertions in that I used them to probe for runtime errors, not for programming errors. I'll remove them from the retail code anyway, so for now, it's just fine that the program terminates if something goes wrong. It helps locating the offending LOC.

Maybe you are looking for

  • Session is not Migrated when I use HttpSessionActivationListener .

    Hi all, I studied about HttpSessionActivation Listener and in order understand it fully I created a simple program . I studied that the listener will be invoked whenever session attribute is migrated from one JVM to another . The following was what I

  • How to change the explain plan for currently running query?

    Hi All, I am using Oracle enterprise 9i edition. I have a query which frames dynamically and running in the database. I noticed a table with 31147758 rows in the query which has no indexes and taking more time to process. I tried to create an INdex o

  • Why doesn't the CreateBackup=True generate a .xlk file?

    What is different in Excel 2010 that is preventing a backup from being created when saving a .xls as a .csv on a network share drive?  If we generate the CSV from Excel 2003, the backups are created.  From Excel 2010, they are not.  It does not matte

  • Expired certificate error for language packages

    I wish to inform the nokia authority,that the language package(UK english Martin) provided for Message Reader app (symbian belle) is showing 'CERTIFICATE EXPIRED' error ,whenever I tried to install the language pack. I request the authority to kindly

  • Can you copy an alias folder from one computer to another?

    I copied files from my iMac to my iBook – However, the "alias" folders didn't copy – did I need to copy the "original" folder(s)?