Matlab / Java API callback - java

I'm designing an API (in Java) and expect to have users accessing the API from Matlab. The problem is that I want the API to provide a piece of functionality like:
javaApi.waitUntilPredicateIsTrue(Predicate<JavaObj> test);
My API (in the background) gets hold of instances of Java Obj (via some mechanism, e.g. polling). I want this API method to block until one of these instances, when passed to the Predicate evaluates to true. If I was calling this API from Java, I'd do:
javaApi.waitUntilPredicateIsTrue(new Predicate<JavaObj>() {
public boolean evaluate(JavaObj jo) {
return "READY".equals(jo.getState());
}
});
You get the idea.
How can this be called from within Matlab? Can I use anonymous inner classes from Matlab? Can I declare a Matlab classdef which extends the interface Predicate (can this cope with the Java generic version)?

That sounds like a tough question. I'm still running R2006b so this may have changed, but it looks like MATLAB will not translate function handles (incl. anonymous functions) and structures into Java objects. I don't know about MATLAB custom classes, since the syntax has changed. Strings, arrays, and cell arrays will translate properly. They don't comment at all on implementing interfaces. (:p :p :p BOO HISS)
edit: just found this page on Matlab Central, it talks about some undocumented interfaces.

Matlab has a much nicer solution than forcing users to create a whole class just to provide a single method. Take a look at their anonymous functions.
Note that anonymous functions in Matlab have odd scoping rules. Make sure you read the "Variables Used in the Expression" section of the linked help page. If you want more traditional lexical scoping, take a look at nested functions.
EDIT:
I am assuming that you will be doing the polling from Matlab, not passing the predicate function to Java. Example:
function waitForPredicate(pred)
while pred
end
end
waitForPredicate(#()javaApi.isMyConditionMet());

Related

Are Kotlin inline functions less expensive than Java anonymous classes?

Heads up: I'm writing some of this from memory so I may have some of the concepts incorrect.
Java has the ability to write an anonymous function. This is useful when you have a listener interface for some kind of event. As an example:
button.setOnClickListener(new View.OnClickListener(View v) {
#Override
public void onClick(View v) {
// handle the action here
}
});
The anonymous listener will be compiled as a class that is called something like OnClickListener$1.class. This is an underlying design decision of the Java language. Everything is an object, even anonymous functions.
This becomes an issue when you want to write a more functionally driven code base. The large amount of anonymous classes creates a large class count, which can be a problem on constrained platforms such as Android.
In Kotlin functions are much more first class from a source code point of view. My question is, does Kotlin compile these functions down to byte code more efficiently than Java does with anonymous classes or will I run into the same issues as the large class count in Java?
Thanks,
The short answer is yes, the Kotlin inline functions are quite cheap.
When an inline function call is compiled, the lambdas passed to the call get inlined into the function body, which is in turn inlined at the call site. This allows the compiler not to generate any additional classes or methods for the lambda bodies.
One of the slides about Kotlin constructs compilation by #yole.
Unfortunately, I found the record only in Russian. The other slides are also of some interest, you can find more about non-inlined lambdas there.
In general, the Kotlin code that uses inline functions with lambdas works faster than the identical Java code with lambdas or Streams. All the code binding is done at compile-time, and there is no runtime overhead of virtual method calls, nor increased methods count, which matters for Android.
The downside of excessive inlining is the code size growth: the common part of the bytecode of an inline function body gets actually duplicated at the call sites. Also, inlining complicates debugging, because the line numbers and the call stack of the code will differ from what was in the source file. Though the IDE support can help here.
I would recommend you to experiment with inline functions yourself: you can easily inspect the resulting bytecode; and, of course, do some benchmarking of your particular use cases where performance matters.
Kotlin has an inline keyword. If you use this keyword, not only does it inline the function but you can treat the lambda body as if it was just a nested scope level, so that you can return from it!
Example (straight from the docs)
fun foo() {
inlineFunction {
return // OK: the lambda is inlined
}
}
Check out the docs for more:
https://kotlinlang.org/docs/reference/inline-functions.html
Edit:
To clarify your exact question about performance, this is the first paragraph from the docs:
Using higher-order functions imposes certain runtime penalties: each function is an object, and it captures a closure, i.e. those variables that are accessed in the body of the function. Memory allocations (both for function objects and classes) and virtual calls introduce runtime overhead.
But it appears that in many cases this kind of overhead can be eliminated by inlining the lambda expressions.
So as far as I can tell yes, it will inline the function and remove any overhead that would otherwise be imposed.
However, this seems to only apply to functions you declare as inline.

How to declare and call a native method containing pointers in java

How to declare and call a native method in c containing pointers using java?
please it is urgent.Because there is no concept of pointers in java i am getting error.
Use JNI(Java Native Interfaces) to call native methods in java. Use this JNI specification pdf as a reference "java.sun.com/docs/books/jni/download/jni.pdf".
There is even a easier approach to the subject, if you or your boss are willing to pay 50$!
Is called eXcelsior xFunction. Try the evaluation version.
Works very well and is simple to use.
The only thing xFunction library does not do have is implementation of address arithmetic in Java, which i assume you will possibly never need.
From their site:
With xFunction, you no longer need to implement those ugly native methods. Instead, you extend and instantiate xFunction classes to create conventional Java objects representing external functions, data structures, pointers, and callbacks. All necessary data conversions and external function calls are done seamlessly by the xFunction library:
import com.excelsior.xFunction.*;
...
/* Call Beep() from KERNEL32.DLL */
xFunction f =
new xFunction( "kernel32",
"int Beep(int,int)" );
f.invoke( new Argument(1770),
new Argument(100) );

c++ templated methods

How are templated methods implemented in C++?
I'm thinking about implementing templates in the JVM and have got a possible implementation thought out for templated classes, but am unsure on methods.
If, for example, you did:
class Test
{
public static boolean isIterable<T>(T variable)
{
return T instanceof Iterable;
}
}
System.out.println(Test.isIterable(new int[] { 0 }));
Would I create a version of Test that replied to int[]? (In my implementation, the class would be named as such: $g$Test$A_Java_lang_int)
Please ignore any problems with generics (such as only requiring boxed objects), as I intend to remove them.
I plan on creating these resolved templates dynamically, and keeping track of the number of references so I can remove them if they are not used. I believe this is how .Net manages it, although I'd be happy to be wrong here!
Would I create a version of Test that replied to int[]?
Essentially, yes. Templates in C++ are purely a compile-time mechanism that uses a (glorified) macro mechanism to generate code based on a template for each type with which it’s instantiated.
(C++ actually does a lot more due to the possibility of specialisation but this is the gist of it.)
I would suggest trying to do this staticly by generating the classes. You might find http://trove.starlight-systems.com/ interesting as it has a templating approach to generating its primitive collections. e.g. TintLongHashMap This doesn't rely on any language features.
I would suggest you work out how to do this staticly before trying to do it dynamicly which is much harder.

Java/Ruby: is there a way to do .constantize or Object.send() in Java?

In Ruby, you can do "var1".constantize to get the actual variable var1.
Ruby also has Model.Send("method name, parameters can be here, etc"), and it would be the same as actually calling that method.
What I want to do.. is... kinda tricky... I want the string "var1 == var2" to be converted to actual variables in my java app, then evaluated.
Is there a way to do this?
Have you considered using JRuby?
As to your questions:
There is no peer to constantize that will allow for an eval like syntax where you can pass in a String and convert it to code in Java. You can do things like Class.forName to load a particular class from a String, but it doesn't sound that is what you are looking for.
You can use the Java reflection API to dynamically invoke methods on a class Check out Jakarta Commons BeanUtils for some utility methods that may help.
In Java, similar behaviour is achieved through the Reflection API. However, since Java is a compiled language, local variables' (within methods, constructors, parameters, etc) information is erased on compilation.
However you still have complete access to class names, hierarchies, methods and fields (class variables).
A good starting point is the Reflection API tutorial or the getClass() method of Object.
In Java if you want a dynamic lookup of variables, you would typically place them in a Map and lookup use the keys of that Map.
Can you explain what you are trying to do in more detail, I suspect what you are trying to do can be done simply a different way in Java.

Java mechanisms at use in lambdaj closures

Lamdbaj allows the definition of closures in the Java language, various examples can be found
here
My question is regarding the underlying Java mechanisms at use, for instance, to define the println closure, the following code is used:
Closure println = closure();
{ of(System.out).println(var(String.class)); }
This closure can be subsequently executed via:
println.apply("foobar");
I am curious as to what mechanisms in Java would allow the call to of(...).println(...) to become associated with the println instance itself.
Naturally, the lambdaj source code is available to read but I was hoping for a slightly higher level explanation if anyone has one. My reflection skills go as far as a bit of introspection and executing methods dynamically.
I am Mario Fusco and I am the main developer of the lambdaj library.
First of all I would like to clarify something: lambdaj is not intended to replace any functional language. As I said last week in my speech at the Jug of Zurich if you have a chance to use Scala, go for it and never look back. Here you can find a resume of my speech where it is clearly stated that:
http://ctpjava.blogspot.com/2009/10/lambdaj-new-trends-in-java.html
I am an happy Scala developer too. But sometimes you are just obliged to develop in Java (in my experience, in the real world, about the 80% of times you cannot choose in which language you have to write your code) and in this case some of the lambdaj features could be helpful (or I hope so). I just wanted to bring to Java some functional features that are totally missing. Of course the result is not completely satisfying mainly due to the limitation imposed by Java itself.
As for the internal lambdaj mechanism, yes it uses a ThreadLocal in order to achieve that result. If you have other questions, curiosities or even better suggestions and constructive critics about lambdaj maybe you could be interested to register yourself to the lambdaj mailing list here:
http://groups.google.com/group/lambdaj
Bye
Mario
Well, of is presumably a static method which is imported statically so it can be called without the enclosing class name. I expect that var is the same. Both methods must return some type which have the methods subsequently called:
public class Printable {
public void println(Var var);
}
public class Fac {
public static Printable of(Object o) {
return new Printable(o);
}
public static Var var(Class<?> clazz) {
return new Var(clazz);
}
}
All of a sudden:
Fac.of(System.out).println(Fac.var(String.class));
Is valid Java. Using static imports, hey presto:
import static Fac.*;
of(System.out).println(var(String.class));
The curly-braces are obviously valid Java as you can add these in any method to aid in defining a lexical sope. This API-design style is called fluent and is best showcased by the JMock testing library.
By the way, if this is supposed to introduce closures to Java, it's quite ridiculous - the syntax is unreadably awful. Their I/O example actually made me laugh out loud. Try Scala!
EDIT - the two println calls are associated I believe because the first sequence of calls allow the library to capture the variables which you have passed in as parameters. These are probably captured in some ThreadLocal structure. When you then call a (also presumably static) println method, the library is using this captured data to actually execute the behaviour at a later point. Also testing related, the EasyMock test framework uses a similar mechanism (which uses Java proxies in the background) to capture expected values.

Categories

Resources