Function pointers (Callback functions) in Java ?

Discussion in 'Java' started by exquisitus, Feb 27, 2005.

  1. exquisitus

    exquisitus Guest

    Any one knows how I can implement callback functions in Java ( I am
    implementing an Observer design pattern and I need to register the
    'update' functions of the "Observables".

    Easy in C++ - don't know how in Java (other than possibly wrapping up
    the function in an object ? - good grief please say it isn't so !)
    exquisitus, Feb 27, 2005
    #1
    1. Advertising

  2. "exquisitus" <> schreef in bericht
    news:cvtcs7$6c9$...
    > Any one knows how I can implement callback functions in Java ( I am
    > implementing an Observer design pattern and I need to register the 'update'
    > functions of the "Observables".
    >
    > Easy in C++ - don't know how in Java (other than possibly wrapping up the
    > function in an object ? - good grief please say it isn't so !)


    If you fear objects, you shouldn't program in Java. :)
    Create an interface ("Observable") that defines the update method.
    Boudewijn Dijkstra, Feb 27, 2005
    #2
    1. Advertising

  3. exquisitus

    HK Guest

    exquisitus wrote:
    > Any one knows how I can implement callback functions in Java ( I am
    > implementing an Observer design pattern and I need to register the
    > 'update' functions of the "Observables".
    >
    > Easy in C++ - don't know how in Java (other than possibly wrapping up


    > the function in an object ? - good grief please say it isn't so !)


    Yes, it is so, and it is sometimes a bit annoying,
    but you get used to it. What most probably want to use
    are inline class implementations (dunno the right term).

    Lets assume your callbacks are defined in an
    interface Oops like this:

    public interface Oops {
    void update(SomeStuff stuff);
    }

    Then you may anytime write something like this:

    Oops callback = new Oops() {
    public update(SomeStuff stuff) {
    // perform update
    };

    This was a quick definition of a class and an object of
    this class, right? Now you can pass your callback around.

    Harald.
    HK, Feb 27, 2005
    #3
  4. exquisitus

    Tilman Bohn Guest

    In message <cvtcs7$6c9$>,
    exquisitus wrote on Sun, 27 Feb 2005 21:08:23 +0000 (UTC):

    > Any one knows how I can implement callback functions in Java ( I am
    > implementing an Observer design pattern and I need to register the
    > 'update' functions of the "Observables".
    >
    > Easy in C++ - don't know how in Java (other than possibly wrapping up
    > the function in an object ? - good grief please say it isn't so !)


    What, you're averse to using objects in an object-oriented language?
    This is of course the standard way of handling callbacks in Java. Why do
    you think this poses a problem? Before answering that, please look at
    anonymous inner classes first. Callbacks are one of the reasons they
    exist.

    --
    Cheers, Tilman

    `Boy, life takes a long time to live...' -- Steven Wright
    Tilman Bohn, Feb 27, 2005
    #4
  5. exquisitus wrote:
    > Any one knows how I can implement callback functions in Java ( I am
    > implementing an Observer design pattern and I need to register the
    > 'update' functions of the "Observables".
    >
    > Easy in C++ - don't know how in Java (other than possibly wrapping up
    > the function in an object ? - good grief please say it isn't so !)
    >


    Its actually very trivial in Java - much like it is in C++.

    However, can you post some example code of how 'you' would implement the
    Observer Pattern in C++. I'm curious because of the tone of your question.

    As for a Java implementation, there is actually one within the JDK you
    can use...

    http://java.sun.com/j2se/1.4.2/docs/api/java/util/Observable.html

    ... or roll your own like it.
    Andrew McDonagh, Feb 27, 2005
    #5
  6. exquisitus wrote:
    > Any one knows how I can implement callback functions in Java ( I am
    > implementing an Observer design pattern and I need to register the
    > 'update' functions of the "Observables".
    >
    > Easy in C++ - don't know how in Java (other than possibly wrapping up
    > the function in an object ? - good grief please say it isn't so !)
    >


    oh, I think I just realised what the tone is about. You are asking for
    call back 'functions' not call back objects.

    To me 'functions' implies that you don't want to create an object that
    registers itself to be called back (on a known Method). You want to
    register a C/C++ function which may not be bound to an object.

    Is this right?

    If so, then you can't do exactly that in Java easily, unless you resort
    to using Reflection. But that way would be messy and silly at best -
    down right sackable at worst.

    To echo the others 'why' question, why the aversion to using an Object?

    Curious

    Andrew
    Andrew McDonagh, Feb 27, 2005
    #6
  7. HK wrote:
    > exquisitus wrote:
    >
    >>Any one knows how I can implement callback functions in Java ( I am
    >>implementing an Observer design pattern and I need to register the
    >>'update' functions of the "Observables".
    >>
    >>Easy in C++ - don't know how in Java (other than possibly wrapping up

    >
    >
    >>the function in an object ? - good grief please say it isn't so !)

    >
    >
    > Yes, it is so, and it is sometimes a bit annoying,
    > but you get used to it.


    In my experience, people who don't understand objects, find it annoying
    and tend never to fully 'get used to it'

    >What most probably want to use
    > are inline class implementations (dunno the right term).


    Anonymous Inner Class

    Which basically means you have defined an unnamed Inner class, because
    it is trivial in size and behavior.

    However, if the Anonymous inner class is to do something substantial,
    then a proper named inner class or even a normal top level class (i.e.
    one in its own .Java file) would be more appropriate.


    >
    > Lets assume your callbacks are defined in an
    > interface Oops like this:
    >
    > public interface Oops {
    > void update(SomeStuff stuff);
    > }
    >
    > Then you may anytime write something like this:
    >
    > Oops callback = new Oops() {
    > public update(SomeStuff stuff) {
    > // perform update
    > };



    using the same example but giving the inner class a name would be...

    class MyCallbackUsingClass {

    public MyCallbackUsingClass() {
    Oops callback = new OopsImplemenation();
    }


    public doSomething() {
    callBack.update(someStuff);
    }

    private Oops callback;


    class OopsImplementation implements Oops {

    public update(SomeStuff stuff) {
    // perform update
    }

    }
    }
    Andrew McDonagh, Feb 27, 2005
    #7
  8. exquisitus

    HK Guest

    OT: discussion style, WAS: Function pointers (Callback functions) in Java ?

    Hi again.

    exquisitus wrote:
    > Easy in C++ - don't know how in Java (other than possibly wrapping up


    > the function in an object ? - good grief please say it isn't so !)


    It is sad that your "good grief" triggered
    so many replies sounding as if
    the writer felt offended.

    I would kindly like to ask those people
    to be more polite and not get upset just
    because someone delivers the slightest
    hint that Java might not be perfect.

    In the end, having functions as first
    class data types is not completely unheard
    of, not only in C/C++.

    Thanks,
    Harald.
    HK, Feb 27, 2005
    #8
  9. Re: OT: discussion style, WAS: Function pointers (Callback functions)in Java ?

    HK wrote:
    > Hi again.
    >
    > exquisitus wrote:
    >
    >>Easy in C++ - don't know how in Java (other than possibly wrapping up

    >
    >
    >>the function in an object ? - good grief please say it isn't so !)

    >
    >
    > It is sad that your "good grief" triggered
    > so many replies sounding as if
    > the writer felt offended.
    >
    > I would kindly like to ask those people
    > to be more polite and not get upset just
    > because someone delivers the slightest
    > hint that Java might not be perfect.
    >
    > In the end, having functions as first
    > class data types is not completely unheard
    > of, not only in C/C++.
    >
    > Thanks,
    > Harald.
    >


    I can't speak for the two others who have replied, but I certainly
    wasn't offended by the Ops post. I was curious however, as to his
    aversion to using an object rather than a function.

    I didn't take his posting to be a swipe at Java's lack of function
    pointer. I took it as them wanting to know how to do something they have
    done in another language, in Java.

    That however, sparked a thought of my own, as to why a function pointer
    is desirable in C++, when the same language supports Object call backs.

    Its merely a question of OO-ness.
    Andrew McDonagh, Feb 27, 2005
    #9
  10. "exquisitus" <> wrote ...
    > Any one knows how I can implement callback functions in Java ( I am
    > implementing an Observer design pattern and I need to register the
    > 'update' functions of the "Observables".
    >
    > Easy in C++ - don't know how in Java (other than possibly wrapping
    > up the function in an object ? - good grief please say it isn't so
    > !)


    It is so. Anonymous innner classes are there exactly to provide
    callbacks. Welcome to Java.
    Brian Hetrick, Feb 27, 2005
    #10
  11. exquisitus

    exquisitus Guest

    Andrew McDonagh wrote:

    > exquisitus wrote:
    >
    >> Any one knows how I can implement callback functions in Java ( I am
    >> implementing an Observer design pattern and I need to register the
    >> 'update' functions of the "Observables".
    >>
    >> Easy in C++ - don't know how in Java (other than possibly wrapping up
    >> the function in an object ? - good grief please say it isn't so !)
    >>

    >
    > Its actually very trivial in Java - much like it is in C++.
    >
    > However, can you post some example code of how 'you' would implement the
    > Observer Pattern in C++. I'm curious because of the tone of your question.
    >
    > As for a Java implementation, there is actually one within the JDK you
    > can use...
    >
    > http://java.sun.com/j2se/1.4.2/docs/api/java/util/Observable.html
    >
    > .. or roll your own like it.


    Thanks for the link. The reason I may have sounded a little 'cheesed
    off' with too much "hand holding" by Java (and by that I mean not really
    allowing you to get close enough to the machine) is this:

    I have a heirarchical ADT whose innermost structure is a set of records.
    Each record (C struct) has several fields and represents data
    received from a real time feed. In C++, I am using the BOOST library to
    allocate a memory pool from which I can request memory slices as and
    when I need it. I can write the data directly from my feed to memory,
    with (almost) no latency. In Java (I am a newbie - so hopefully you can
    correct me), I find that I have to wrap up the ADT which is so naturally
    a struct, into a heavy, clumsy object. Everytime I receive data, I have
    to create a new data object (an encapsulation of the C struct) and then
    add it to my array. The perfomance hit on creating so many objects is
    (unsuprisingly) abysmal when compared to the C++ code. In practise, I
    can expect to receive about 50 such records per second, and can receive
    as much as 50,000 records in total. The thought of spawning 50 new
    object a second - not to mention having 50,000 bloated objects hanging
    around in memory is not a pleasing prospect.

    So I will say once again (and this is not to encite the wrath of the
    more experienced Java programmers). Please tell me it isn't so (I will
    gladly accept a better solution if there is one - I have no ego as far
    as this is concerned). There must be another way - a better way of
    dumping these records into memory without having to create a new object
    every time the data is received.

    I look forward to your response.
    exquisitus, Feb 28, 2005
    #11
  12. On Mon, 28 Feb 2005 00:52:04 +0000, exquisitus wrote:

    > So I will say once again (and this is not to encite the wrath of the
    > more experienced Java programmers). Please tell me it isn't so (I will
    > gladly accept a better solution if there is one - I have no ego as far
    > as this is concerned). There must be another way - a better way of
    > dumping these records into memory without having to create a new object
    > every time the data is received.


    Do a search on "java object pool" and see what you find. If you design
    your ADT class properly, you can re-use the instances instead of having to
    create new ones every time. I am unsure if the cost of re-initializing an
    ADT outweighs the benefits of not having to allocate a new object.

    HTH,
    La'ie Techie
    =?UTF-8?b?TMSByrtpZSBUZWNoaWU=?=, Feb 28, 2005
    #12
  13. exquisitus

    knightowl Guest

    > class MyCallbackUsingClass {
    >
    > public MyCallbackUsingClass() {
    > Oops callback = new OopsImplemenation();
    > }
    >
    >
    > public doSomething() {
    > callBack.update(someStuff);
    > }
    >
    > private Oops callback;
    >
    >
    > class OopsImplementation implements Oops {
    >
    > public update(SomeStuff stuff) {
    > // perform update
    > }
    >
    > }
    > }


    I am new the Java, and I am trying to get a handle on the above
    callback example. I wrote a parsing engine that used call back
    functions, and I used reflection (a sackable offense as I am now aware
    of it).

    In the above I don't see the Opps interface. I guess i am not not
    making the connection

    Thanks
    HFC
    knightowl, Feb 28, 2005
    #13
  14. exquisitus

    HK Guest

    exquisitus wrote:
    > correct me), I find that I have to wrap up the ADT which is so

    naturally
    > a struct, into a heavy, clumsy object. Everytime I receive data, I

    have
    > to create a new data object (an encapsulation of the C struct) and

    then
    > add it to my array. The perfomance hit on creating so many objects is


    > (unsuprisingly) abysmal when compared to the C++ code. In practise, I


    > can expect to receive about 50 such records per second, and can

    receive
    > as much as 50,000 records in total. The thought of spawning 50 new
    > object a second - not to mention having 50,000 bloated objects

    hanging
    > around in memory is not a pleasing prospect.


    Lets compare a C struct to a Java object. The memory
    occupied by the fields is pretty much the same.
    The Java object typically has one additional field, a pointer
    to the Class representation to which the object belongs.

    Looking at an array of those things, Java needs
    another pointer to point to the object, because
    objects themselves are not put into the array, only
    ever the pointers to them.

    >From the memory perspective this is an overhead of

    8 bytes and it depends of course on your setting
    whether this is tolerable or bloated.

    Now for the performance: In C, malloc and free are
    not exactly cheap operations as you will see when
    profiling software which does a lot of them.
    In Java, free (i.e. garbage collection) is probably
    a bit more expensive than what C free does. On the
    other hand, a `new' is less expensive than malloc
    because garbage collection arranges free blocks
    of memory much more neatly than free does.

    The bottom line is in both situations: don't
    request and abandon memory unnecessarily. In C++
    you work with a memory pool. In Java you can do
    the same. There are implementations of it, but
    depending on your setting, you just preallocate
    a lot of the objects you need and when it
    comes to receiving the data, just fill them.

    Harald.
    HK, Feb 28, 2005
    #14
  15. exquisitus

    Chris Uppal Guest

    exquisitus wrote:

    > In practise, I
    > can expect to receive about 50 such records per second, and can receive
    > as much as 50,000 records in total. The thought of spawning 50 new
    > object a second - not to mention having 50,000 bloated objects hanging
    > around in memory is not a pleasing prospect.


    50 objects per second is trivial. 50K objects is trivial. (Unless they are
    really big, but if they are then the fixed overhead of "objectness" will be
    trivial[*].) If your app is running slowly then its not because of the use of
    objects.

    ([*] Though, in that case, the cost of double intialisation may not be)

    A couple of people have suggested looking into object pooling. That /might/
    help but:

    a) It is very difficult to estimate how object pooling will interact with
    generational GC. It could as easily kill your performance as help it.

    b) As I said above, I don't think that object creation is your problem.


    > a heavy, clumsy object.


    I think you need to spend some time re-tuning your intuitions about where and
    what the costs are.

    BTW, you come across as being strongly averse to objects. (Fair enough, I
    dislike spiders myself...) But if that's the case, why /are/ you trying to use
    Java ?

    -- chris
    Chris Uppal, Feb 28, 2005
    #15
  16. exquisitus

    exquisitus Guest

    Chris Uppal wrote:
    <snip>
    >
    > BTW, you come across as being strongly averse to objects. (Fair enough, I
    > dislike spiders myself...) But if that's the case, why /are/ you trying to use
    > Java ?
    >

    </snip>

    WHY is everyone jumping to the conclusion that I am adverse to objects?.
    I simply dont like the idea of spawning a new object (with all the
    concomitant baggage) when a simple struct will do. I may not be up to
    date with Java's latest performance figures etc, but coming from a
    strong C++ (which allows you much more freedom - admitedly a double
    edged sword if you dont know what you're doing), I must admit that I
    view Java quite suspisiously when it comes to memory operations and
    sheer performance - there I said it.

    As to why I'm using Java - I mentioned in a previous post that Java has
    several good points in its favour - enterprise computing, internet and
    network aware (almost out of the box) etc - and not to mention the
    seductive compile once run anywhere slogan. That is the main reason why
    I am taking a look at Java. I must admit though that some of you guys
    are *way* too sensitive about Java. It's just a language for Christ's
    sake !.

    I'm trying to learn Java by jumping in at the deep end - If i ask a
    question (no matter how silly it may seem), it is because I have become
    unstuck and done a google search - which yielded no useful results. Most
    of the stuff that I take for granted in C++ appears missing in Java
    (1.4): Type safe enumerations, variable length args, Template Classes,
    proper string formating ala 'printf', and of course my beloved pointers
    and memory adressing which I'll simply have to forget when using Java.
    So by the time I come to ask a question, I'm pretty frustrated at the
    (aparent) short comings of the language - if that makes me sound
    critical, it has not been my intention and I apologize. But likewise,
    you guys have to losen upa nd stop thinking that everyone is critisizing
    your 'beloved' Java. Like I said, its only a language ...
    exquisitus, Feb 28, 2005
    #16
  17. F'up set.

    exquisitus wrote:
    > WHY is everyone jumping to the conclusion that I am adverse to objects?.


    Because that's what you write. Quote:

    |> There must be another way - a better way of dumping these records
    into memory without having to create a new object every time the data is
    received.


    > I simply dont like the idea of spawning a new object (with all the
    > concomitant baggage) when a simple struct will do.


    Then use another language.

    > I may not be up to
    > date with Java's latest performance figures etc,


    Then why not familiarize yourself with the facts first, before whining
    about things you don't know? Every other week someone like you comes
    here, anonymously trolls and claims ignorance, but tries to tell us how
    Java should be and how it should work, while it in fact it works quite
    fine for many of us. There are so many of your kind, that many of us
    have long lost patience.

    People in this group will be the first to admit that Java has flaws, but
    trust us, the regulars here are well aware of them, and don't need to be
    reminded of them every week.

    > but coming from a
    > strong C++ (which allows you much more freedom - admitedly a double
    > edged sword if you dont know what you're doing), I must admit that I
    > view Java quite suspisiously when it comes to memory operations and
    > sheer performance - there I said it.


    comp.lang.java.advocacy is next door. We assume people are coming here
    to the programming group want to program Java and not have a pissing
    match Java vs. C++. That's what advocacy groups are for.

    > I must admit though that some of you guys
    > are *way* too sensitive about Java. It's just a language for Christ's
    > sake !.


    It is you who seems to be very sensitive about criticism. People here
    just asked questions and told you facts.

    > I'm trying to learn Java by jumping in at the deep end - If i ask a
    > question (no matter how silly it may seem),


    Use comp.lang.java.help if you want to ask beginners questions. Use
    comp.lang.java.advocacy for a Java rant.

    /Thomas
    --
    The comp.lang.java.gui FAQ:
    ftp://ftp.cs.uu.nl/pub/NEWS.ANSWERS/computer-lang/java/gui/faq
    Thomas Weidenfeller, Feb 28, 2005
    #17
  18. "exquisitus" <> wrote in message
    news:cvv5d1$qjm$...
    >
    >
    > Chris Uppal wrote:
    > <snip>
    > >
    > > BTW, you come across as being strongly averse to
    > > objects. (Fair enough, I dislike spiders myself...) But
    > > if that's the case, why /are/ you trying to use Java ?
    > >

    >

    <SNIP>
    >
    > Most of the stuff that I take for granted in C++ appears
    > missing in Java (1.4): Type safe enumerations, variable
    > length args, Template Classes, proper string formating ala
    > 'printf',
    >


    The latest Java version - 1.5 - has added many of these facilities, though,
    in the case of generics, think templates for container type safety, rather
    than template metaprogramming support.

    The following link may be of use:

    http://java.sun.com/j2se/1.5.0/docs/relnotes/features.html

    >
    > and of course my beloved pointers and memory
    > adressing which I'll simply have to forget when using
    > Java.
    >


    When learning another language one should be prepared for a mindset change,
    so being receptive to new ideas / techniques [though, of course, in a
    healthily skeptical way ;) !] is of great help [though not necessaily easy
    to do].

    All the best with your Java explorations.

    Cheers,

    Anthony Borla
    Anthony Borla, Feb 28, 2005
    #18
  19. exquisitus wrote:

    > The perfomance hit on creating so many objects is (unsuprisingly)
    > abysmal when compared to the C++ code.


    Performance problems are a reasonably common result of attempting to
    write C / C++ code in Java. Do not be fooled by the similarities in
    syntax -- there are deep differences between C and C++ on the one side,
    and Java on the other. As a result, the better ways of implementing
    algorithms often differ, and using one language's idioms in the other
    leads to disappointment.

    Secondly, unless you have profiled the Java version of your application,
    do not presume that you know where its bottlenecks are or why the
    performance is poor. In particular, object creation is very fast in
    modern VMs, and is unlikely to be the source of your performance
    problem. There are a whole host of of other things that _could_ be the
    problem; top on my list of wild guesses would be frequent reallocations
    (and associated copying) of the array in which you are holding all these
    objects.

    --
    John Bollinger
    John C. Bollinger, Feb 28, 2005
    #19
  20. exquisitus sez:

    > Each record (C struct) has several fields and represents data
    > received from a real time feed. In C++, I am using the BOOST library to
    > allocate a memory pool from which I can request memory slices as and
    > when I need it. I can write the data directly from my feed to memory,
    > with (almost) no latency. In Java (I am a newbie - so hopefully you can
    > correct me), I find that I have to wrap up the ADT which is so naturally
    > a struct, into a heavy, clumsy object. Everytime I receive data, I have
    > to create a new data object (an encapsulation of the C struct) and then
    > add it to my array. The perfomance hit on creating so many objects is
    > (unsuprisingly) abysmal when compared to the C++ code. In practise, I
    > can expect to receive about 50 such records per second, and can receive
    > as much as 50,000 records in total. The thought of spawning 50 new
    > object a second - not to mention having 50,000 bloated objects hanging
    > around in memory is not a pleasing prospect.
    >
    > So I will say once again (and this is not to encite the wrath of the
    > more experienced Java programmers). Please tell me it isn't so (I will
    > gladly accept a better solution if there is one - I have no ego as far
    > as this is concerned).


    It is so. However, a data object does not have to be fat and clumsy,
    and 50,000 records is nothing. You shouldn't worry until you get to
    the order of 10^6 records.

    ....There must be another way - a better way of
    > dumping these records into memory without having to create a new object
    > every time the data is received.


    Column-wise arrays of primitive types.

    I wouldn't use Java for real-time data acqusition (if that's what
    you're doing) -- there's no guarantee that it won't stop reading
    & go collect garbage in the middle of input.

    Dima
    --
    All whitespace is equivalent except in certain cituations
    -- ANSI C standard committee
    Dimitri Maziuk, Feb 28, 2005
    #20
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. S?ren Gammelmark
    Replies:
    1
    Views:
    1,884
    Eric Sosman
    Jan 7, 2005
  2. Marc Thrun
    Replies:
    15
    Views:
    857
    Tim Rentsch
    Oct 4, 2005
  3. newbie

    Pointers to char pointers in functions

    newbie, Sep 18, 2006, in forum: C Programming
    Replies:
    9
    Views:
    306
    August Karlstrom
    Sep 24, 2006
  4. cerr

    pointers, pointers, pointers...

    cerr, Apr 7, 2011, in forum: C Programming
    Replies:
    12
    Views:
    672
  5. ajaybgr
    Replies:
    18
    Views:
    965
    Philip Lantz
    Sep 7, 2012
Loading...

Share This Page