Method.invoke() thread save ?

Hi to you all,
Is the method invoke on the Object Method in the java.lang.reflect package threadsafe ?
Greetz-tbone

I'have created a with a college a ReflectionMap where getter and setter maps to the javabean properties
using reflection at creation time the map cache the methods of the underlaying object
now we want to use it i a multiple thread context
where more than one thread can access the map a time
if the implementation of Method is threadsafe then we do not need synchronisation else
we must synchronize our map.
and sinds that synchronisation is a performence bottleneck i would like to live it out.
Tbone

Similar Messages

  • Method.invoke hangs?

    I'm trying to send a Class over a network, then invoke a Method inside the class.
                            final Method command = clazz.getDeclaredMethod("exec");
                            try {
                                System.out.println("Invoked0");
                                command.invoke(null);
                                System.out.println("Invoked1");
                            } catch (Exception e) {
                                throw new RuntimeException(e);
                            }Only Invoked0 prints, and there is no Exception. Whats wrong?
        class CommandClassLoader extends ClassLoader {
            public Class<?> defineClass0(String name, byte[] b, int off, int len) {
                return defineClass(name, b, off, len);
        }

    Oops, didn't realize I was throwing there, its printing a NPE.
    java.lang.NullPointerException
            at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
            at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
            at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
            at java.lang.reflect.Method.invoke(Method.java:597)
            at colby.client.Client$1$2.run(Client.java:63)
            at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:441)
            at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
            at java.util.concurrent.FutureTask.run(FutureTask.java:138)
            at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:98)
            at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:207)
            at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
            at java.lang.Thread.run(Thread.java:619)That doesn't really make sense though? Why would it be happening there?

  • Method.invoke hangs. HELP

    that is:
    Method.invoke(obj,args)
    It works just fine the first dozen or 2 times, same obj, same args. No prob.
    Then it hangs.
    No exception message. nothing. It just stops at invoke. And the Task Manager says the thread is eating 99% of the CPU, so it's spinning away in some loop I guess. The method getting invoked DOES NOT get called. It's definitely hanging inside invoke somewhere. Is this a bug?

    one more clue: There're 100-200 threads calling Method.invoke when the hang happens. The hang is permanent as far as I can tell. I've tried using synchronize in various ways. No luck.

  • How to trap null return values from getters when using Method.invoke()?

    Hi,
    I am using Method.invoke() to access getters in an Object. I need to know which getters return a value and which return null. However, irrespective of the actual return value, I am always getting non-null return value when using Method.invoke().
    Unfortunately, the API documentation of Method.invoke() does not specify how it treats null return values.
    Can someone help?
    Thanks

    What do you get as a result?I think I know what the problem is.
    I tested this using following and it worked fine:
    public class TestMethodInvoke {
    public String getName() {
    return null;
    public static void main(String args[]) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
    Object o = new TestMethodInvoke();
    Class cls = o.getClass();
    Method m = cls.getMethod("getName", (Class[]) null);
    Object result = m.invoke(o, (Object[])null);
    if (result == null) {
    System.err.println("OK: Return value was null as expected");
    else {
    System.err.println("FAILED: Return value was NOT null as expected");
    However, when I use the same technique with an EJB 3.0 Entity class, the null return value is not returned. Instead, I get a String() object. Clearly, the problem is the the EJB 3.0 implementation (Glassfish/Toplink) which is manipulating the getters.
    Regards
    Dibyendu

  • Java.lang.NoSuchMethodException Using Method.invoke(...)

    I try to use Method.invoke() to invoke a method from a class. The method
    has parameters with type JTextArea and JMyFrame, but I got the error
    messages java.lang.NoSuchMethodException . Any ideas???
    If I remove parameter "JFrame mainFrame" in start() method and it is working fine. Not sure why JMyFrame will throw this exception, as JMyFrame is derived from JFrame class
    public class MyFrame extends JFrame
         try
    ClassLoader loader
    = new MyClassLoader(Integer.parseInt("3"));
    Class c = loader.loadClass("NewMenuPackage.NewMenu");
    Class[] params = { JTextArea.class, JMyFrame.class };
         Method m = c.getMethod("start", params);
         Object obj = c.newInstance();
    m.invoke(obj,
         new Object[] {
              textArea,
              JMyFrame.this
    catch (Throwable e)
    JOptionPane.showMessageDialog(this, e);
    package NewMenuPackage;
    import javax.swing.*;
    public class NewMenu
         private static JMenuItem menuItem = new JMenuItem("New Menu");
         public static JMenuItem getJMenuItem()
              return menuItem;
         public static void start(JTextArea textArea, JFrame mainFrame)
              System.out.println("NewMenu->start()...");
    }

    Your "params" Class array has to specify the exact classes of the method, not subclasses. The line that is causing the NoSuchObjectException to be thrown is "c.getMethod("start", params);".
    You have to write your own reflection utility methods to find a method that matches on parameter subclasses.

  • Dynamic casting of Method.invoke() return

    Can anyone clue me in on how to cast the return of Method.invoke() based on Method.getReturnType() or whatever else might work dynamically....that is without knowing which method until runtime?
    Thanks,
    Brad

    Thanks for helping me get a grip....makes perfect sense, I guess I was just wondering how far you could take the runtime decisions thing.
    Can I say that, ( and it seems obvious but... ), programatic flexibility and runtime decision making can only be taken so far - and has to be made in the context of certain presumptions at compike time.
    I can see that in implementing the:
    <jsp: setParameter name="myBean" property="*" />
    Presumptions are made that the values passed to
    the bean setter methods will be String objects and that the
    values returned from the:getter methods using:
    <jsp: getProperty name="myBean" property="whaterver" />
    will also be String objects.
    Reality check?
    Thanks again,
    Brad

  • Method.invoke

    Hi,
    I'm trying to dynamically load various classes at runtime but have encountered a problem with the Method.invoke() method.
    Class c = Class.forName( "car" );
    Method m = c.getDeclaredMethod("Execute", new Class [] { String.class } );
    object res = m.invoke( Object obj, Object[] arg); // here is the problemI do not know what parameters to set inside Method.invoke(). Looking for some advice here. All the classes that I want to load implement an interface;
    interface loadplugin
       boolean Execute(String str);
    }Any suggestions?

    Hi,
    You put the parameters the Method needs to the Object [] -
    This is a call you know:
    loadplugin myLoadPlugin = new LoadpluginImplementingClass();
    boolean result = myLoadplugin.Execute("Hallo World");The corrsponding call to the Method object is:
    Boolean result = (Boolean)m.invoke(myLoadpugin, new Object[]{"Hallo World"}); The Method object only can hanlde Object types. For any standard data type (int, boolean, double, etc.) the corresponding Wrappers have to be used. So the return in case of the Method-Object call is Boolean, not boolean.
    I hope this helps,
    Lars.

  • How to know whether a method is thread-safe through the java-doc?

    In some book, it says that SAXParserFactory.newSAXParser() is thread-safe,but in the java-doc,it doesn't say that.
    newSAXParser
    public abstract SAXParser newSAXParser()
    throws ParserConfigurationException,
    SAXExceptionCreates a new instance of a SAXParser using the currently configured factory parameters.
    Returns:
    A new instance of a SAXParser.
    Throws:
    ParserConfigurationException - if a parser cannot be created which satisfies the requested configuration.
    SAXException - for SAX errors.
    I want to know, how to know whether a method is thread-safe?

    System.out is a PrintStream object. None of the methods there use the synchronized modifier, but if you look in the source code, you will find out it is thread-safe, because it will use synchronized blocks whenever it writes some text.
    The source code is in the src.jar file which you can extract.
    I didn't find any comments about that PrintStream is thread-safe in the API.

  • How can I get to know if a method is threads-safe?

    Hi, there.
    How can I get to know if a method is threads-safe?
    For example, in two different threads, is System.out.print() method safe or not?And where can I find the information with regard to this?
    thanks very much.

    System.out is a PrintStream object. None of the methods there use the synchronized modifier, but if you look in the source code, you will find out it is thread-safe, because it will use synchronized blocks whenever it writes some text.
    The source code is in the src.jar file which you can extract.
    I didn't find any comments about that PrintStream is thread-safe in the API.

  • Using java.lang.reflect.Method.invoke on a static method?

    This is probably a FAQ, but I am finding it impossible to construct a search which answers this question for me.
    How do I call java.lang.reflect.Method.invoke on a static (e.g. class) method? Is it even possible?
    Thanks,
    dwh

    Is this of any help?
    http://www.esus.com/javaindex/j2se/jdk1.2/javalang/reflection/reflection.html
    Cheers,
    Joris

  • Using Reflection - Method.invoke()

    Hi all,
    Facing a problem in using the Reflection API. Can anyone tell me how to use the invoke, which is available with Method. Problem statement. - I want to create a method. And then invoke that method using method1. invoke. But this can take only the following arguments - (Object, Object [ ] ). I cant figure out why I need to pass on an object ? and an array of objects ?

    If you read the docs for Method.invoke, you'll see that the first argument is the object on which you wish to invoke the method, and the second argument is the parameters (with primitives wrapped appropriately).
    foo.bar("abc", 123);
    // becomes
    meth.invoke(foo, new Object[] {"abc", new Integer(123) }); (if I haven't screwed up the syntax of the array initialization)
    http://java.sun.com/docs/books/tutorial/reflect/

  • Is Method.invoke (Object,Class[]) efficient

    hi
    How efficient is the method invoke compared to explicit method calling?
    thanks

    I cna't give any solid numbers either, but when I've used it I've noticed it to be much slower than directly invoking the method. Ballpark I'd guess 5 times as much overhead, but don't hold me to that. Of course, if the work your method does is large compared to method invocation overhead, then it shouldn't really matter.

  • Instance methods faster than sync. static methods in threaded env?

    consider the following please:
    (-) i have "lots" of instances of a single Runnable class running concurrently..
    (-) each instance uses a common method: "exponential smoothing" and they do a lot of smoothing.
    so:
    (option #1): include a "smooth()" instance method in the Runnable class.
    (option #2): include a "smooth()" synchronized static method in the Runnable class.
    (option #3): create a MathUtility class, and have "smooth()" as an instance method in this class.
    (option #4): make "smooth()" a synchronized static method in the MathUtility class.
    from OOP point of view, i think i should externalize "smooth()" to a MathUtility class, and then make
    is "synchronized static".
    but then from a performance point of view....
    would not it be optimal to make "smooth()" an instance method in MathUtility and then have each
    instance of the Runnable create its own MathUtility instance so that each thread has its own copy
    of the "smooth()" method??
    well, i can't image there would be a measurable difference so maybe i should not post.
    but, if there is a flaw in my thinking, please let me know.
    thanks.

    kogose wrote:
    from OOP point of view, i think i should externalize "smooth()" to a MathUtility class, and then make
    is "synchronized static".From an OOP point of view you should probably have a class that represents the data that provides a (non-static) smooth() method that either modifies the data or returns a new smoothed data object (depending on whether you want your data objects to be immutable or not).
    but then from a performance point of view....
    would not it be optimal to make "smooth()" an instance method in MathUtility and then have each
    instance of the Runnable create its own MathUtility instance so that each thread has its own copy
    of the "smooth()" method??No, methods are not "copied" for each instance. That just doesn't happen.
    well, i can't image there would be a measurable difference so maybe i should not post.If you don't know, then you should probably try it.
    but, if there is a flaw in my thinking, please let me know.The flaw in your thinking is that you can think that you can intuitively grasp the difference in performance of a change at that level.
    I have yet to meet anyone who can reliably do that.
    Performance optimization is not an intuitive task at that level and you should never do performance optimizations without proving that they are improvements for your particular use case.
    First part: Is the smooth() method really thread-unsafe? Does it use some shared state? My guess would be that it uses only local state and therefore doesn't need any synchronization at all. That would also be the fastest alternative, most likely.

  • Refer to a JTabbedPane from the porgram /&what is the first method invoked?

    Hi there,
    I have been researching for this for a while and couldn?t find the answer, maybe some of you guys can help.
    Situation: I have a program with some JTabbedPane in it
              panel.setLayout(new BorderLayout());
              JTabbedPane pane = new JTabbedPane();
              pane.setTabPlacement(JTabbedPane.LEFT);
              pane.setFont(new Font("Times New Roman", Font.PLAIN, 16));
              pane.add("User", userPanel);
              pane.add("Group Type", groupPanel);
              pane.add("Agent", agentPanel);
              panel.add(pane, BorderLayout.CENTER);
    Question1: sometimes, when the user clicks on JButton, I want to refer him directly to a different ?JTabbedPane?. Meaning, I don?t want him to physically press the ?JTabbedPane? to get there, but I want the program to take him directly to the relevant section. how to do that?
    Quesiotn2: what is the first method invoked when referred to a JTabbedPane. Or, how can I count how many times the users has referred to a particular section.
    Thanks for any help :-)
    dgz

    panel.setLayout(new BorderLayout());
    JTabbedPane pane = new JTabbedPane();
    pane.setTabPlacement(JTabbedPane.LEFT);
    pane.setFont(new Font("Times New Roman", Font.PLAIN,
    16));
    pane.add("User", userPanel);
    pane.add("Group Type", groupPanel);
    pane.add("Agent", agentPanel);
    panel.add(pane, BorderLayout.CENTER);
    Question1: sometimes, when the user clicks on JButton,
    I want to refer him directly to a different
    ?JTabbedPane?. Meaning, I don?t want him to physically
    press the ?JTabbedPane? to get there, but I want the
    program to take him directly to the relevant section.
    how to do that?
    Try this tabPane.setSelectedIndex(anIndex) //eg a number between 0 and tabPane.getTabCount
    Quesiotn2: what is the first method invoked when
    referred to a JTabbedPane. Or, how can I count how
    many times the users has referred to a particular
    section.You can get the component at an index, check if it is showing and update a count variable eg
    Vector counter = new Vector();
    public void checkVisibleTab() {
    for(int x = 0; x < tabPane.getTabCount(); x++) {
       if(tabPane.getComponentAt(x).isShowing())
          counter.addElement( new Integer(x) );
    } You can then iterate through the vector and find how many times a particular number appears and use it for your specific purpose.
    ICE

  • How to stop an execution from a method and thread?

    1,
    public void method(){
    if( something is true)
    //I want to stop this method
    //or if something is false, go on
    blablablablabla
    }Does any one know how to solve the above??
    2,
    Thread t = new Thread(){
    public void run(){
    if( something is true)
    //I want to stop and kill this Thread
    //or if something is false, go on
    blablablablabla
    }Again, how do I solve the above??
    I know this is very simple, but I just hit a wall when I encounter this on making a program for my project.
    please help
    thanks alot

    warnerja, for the method, I have tried "return" but
    it does not work... will it work on the run method of
    thread object??
    Secondly, doesn't "break" keyword only stops the
    execution of a loop/condition, but not the method's
    scope??yes. break breaks the loop. I thought your method doesnt have any other code except the condition.
    use return with thread.

Maybe you are looking for

  • How do I delete someone else's iCloud account off my iPhone without their password?!

    How do I delete someone else's iCloud account off my iPhone without their password?!

  • Date and Time in the flat file

    Hi All, I am trying to design a flow which will get data from a flat file. The file has a field which contains both the time and date. How can I handle this in BW? Do I need to creat 2 infoobjects and split the flat file field in start routine or tra

  • Cross Company Posting

    I have two sales area 1000+10+10 2000+10+10 one document type ZOR 1000 sales organization is assign to co. code 1000 2000 sales organization is assign to co. code 2000 Is it possible if I am using any unique document type lets say ZOR for sales area

  • Adobe Form -Interactive -Subform dissappear after Click

    Hi. I have a Interactive form with a Native submit button with single MAIN view . I am poupulating the form intially in WDOINIT method & I am trying to do some calculations on the form using submit click. Here is what i am doing onclick.After I click

  • Top 10 clients

    Hi , I have a report with top 10 clients, but it is displaying only top 7 clients even though enough data is available. Can anyone suggest on this Regards, Vengatesh.