Akka actors and aroundReceive() method - java

I'm trying to learn Akka (with Java) and understand some code. I have seen something like this, this method signature in a Actor class :
#Override
public void aroundReceive(PartialFunction<Object, BoxedUnit> receive, Object msg)
I've never heard of that method before and don't understand it. What is the purpose of that method ? Where does this PartialFunction<Object, BoxedUnit> receive argument comes from ? I thought it was up to the programmer to implement receive object.

As for PartialFunction<Object, BoxedUnit>, the receive function in an (untyped) actor is an instance of that (this is made abundantly clear in the Scala API, and somewhat less-so in the Java API).
An Actor implementing this (typically via a Scala mixin or extending an abstract class which overrides it) would take the receive function from the actor implemented by the programmer and intercept calls to certain messages (e.g. timing messages) or do pre-/post-processing of messages which are passed onto the given receive.
PartialFunction<Object, BoxedUnit> basically means:
this is a function which doesn't promise to have a result for any particular input; it's the responsibility of the caller to check beforehand (isDefinedAt) if the function will have a result or to accept that the function will throw an exception. (PartialFunction: a function which is not defined over the entirety of its domain)
Object (or in Scala terms Any (technically AnyRef, but autoboxing lets us forget that for a moment)): the function can theoretically accept anything
BoxedUnit indicates that the function returns no useful result (Unit in Scala is like void in Java, but is actually an object (a singleton to be precise)).
(to some extent PartialFunction<Object, BoxedUnit> is the type which tells us and the compiler the least information possible).

First, I am using Akka in Scala, and not in Java. I hope this answer will give you a lead.
In Scala, this method is #InternalApi. The docs of that in Scala is:
Marks APIs that are considered internal to Akka and may change at any point in time without any
warning.
For example, this annotation should be used when the Scala {#code private[akka]} access
restriction is used, as Java has no way of representing this package restricted access and such
methods and classes are represented as {#code public} in byte-code
One purpose of this method is to wrap the receive method with custom behaviour. You can see an example for that in the Timers trait.

Related

callback vs lambda in Java

Spring bean lifecycle documentation often mention callback methods.
While trying to find the meaning of callback, I came through few links that mention it is passing of one function as an argument to another, which could be achieved through interfaces in Java.
I am confused, if this is callback then what are lambda expression and functional interfaces ? Are they same or different?
Callback is a pattern where you pass a function somewhere and it gets called later.
Functional interfaces are a way of specifying what kind of function you expect.
A lambda is a quick way of implementing a functional interface. Lambdas are useful if you want to use callbacks.
For example:
Suppose I am going to generate a message at some point in the future, and you want to be told when it happens. I have a method that lets you give me a function to call when the message is ready.
public void callThisWithMessage(Consumer<String> messageConsumer);
You give me a message consumer, and I will call it later when the message is ready. This is an example of a callback.
The type of function you can give to me here is specified by the Consumer interface, which is a functional interface. This particular functional interface says that it has a method that accepts a parameter (in this case a string).
If you want to use my callback service, you can implement a consumer using a lambda function.
callThisWithMessage(msg -> System.out.println("Message received: "+msg));
This creates a lambda function that implements the functional interface Consumer<String>, and passes that to my method for subsequent callback.
Lambda expressions are one of several ways to implement functional interfaces.
Functional interfaces are used as callbacks, but not all callbacks are functional interfaces. Interfaces used as callbacks can have multiple abstract methods, while functional interfaces can only have a single abstract method.

Private constructor defined in FileNotFoundException?

Randomly I came across this site: http://resources.mpi-inf.mpg.de/d5/teaching/ss05/is05/javadoc/java/io/FileNotFoundException.html
The class FileNotFoundException has three defined constructors:
FileNotFoundException()
Constructs a FileNotFoundException with null as its error detail message.
FileNotFoundException(String s)
Constructs a FileNotFoundException with the specified detail message.
private FileNotFoundException(String path, String reason)
Constructs a FileNotFoundException with a detail message consisting of the given pathname string followed by the given reason string.
But the last constructor is defined as private?
Again, here: http://www.docjar.com/html/api/java/io/FileNotFoundException.java.html we can see the full class definition. There is no other code, so the singleton pattern is obviously not used for that case, nor we can see, why it should be prevented to instantiate the class outside of the object, nor is it a factory method, static (utility class) method or an constants-only class.
I am C# dev so I might not be aware about some stuff that is going on here but I would still be interested why it is defined as private, for what it is used and if there is any example or an use case for that last constructor.
The comment mentions:
This private constructor is invoked only by native I/O methods.
Anybody explain this a bit further in detail?
Keep in mind: a lot of the libraries of the JVM are written in Java, like that exception. But when interacting with "the rest of the world"; sooner or later Java doesn't do any more - there is a need to talk C/C++ in order to make real system calls.
Meaning: certain operations related to file IO can't be completely implemented in Java. Thus native code comes in (compiled binaries). But of course, such a call can fail as well. But then one needs a mean to communicate that on the Java side - in other words: an exception needs to be thrown.
Given the comments that you are quoting this seems pretty straight forward: when certain IO related native operations fail; they will use that private constructor to create the exception that is then thrown at "you". And yes, native methods can call private methods!
Edit: but when looking at the implementation - there is really nothing specific about that constructor One could easily construct such an exception using the exact same message that this private ctor would create.
private FileNotFoundException(String path, String reason) {
super(path + ((reason == null)
? ""
: " (" + reason + ")"));
}
So, my personal guess: this could even be some "leftover". Something that had a certain meaning 15 years ago; but isn't of "real meaning" any more. Or even more simple, a convenience method allowing native code to either pass a null or a non-null reason string.
The constructor in question is private so that no other class can use it to initialize an instance. It could, in principle, be used by the class itself -- that sort of thing is not unusual when one constructor is intended to be invoked by another, or by a factory method.
In this case, however, the documentation presents a different reason, which you in fact quoted:
This private constructor is invoked only by native I/O methods.
That seems clear enough to me, but I suppose your confusion may revolve around details of Java access control -- in particular, that it does not apply to native methods. Thus the native methods by which various I/O functionalities are implemented can instantiate FileNotFoundException via the private constructor, regardless of which class they belong to.

What is the internal identification of a Java method?

As we know, in Java, method name is not sufficient to distinguish different methods.
I think (may be wrong), to distinguish a method, it needs the following info:
(className, methodName, methodParameters)
Further,
how to identify a method more efficiently internally?
I heard of "method id". Does it mean there is a mapping between the above triple and an integer, so JVM use only method id after parsing?
If so, is it resided in symbol table?
Thanks!
It's a CONSTANT_NameAndType_info Structure pointing at a method descriptor.
It pretty much consists of the method name, the parameter types, and (somewhat surprisingly) the return type.
I do not understand very well what you are trying to do but I think there are some possible answers nonetheless:
You may be interested in the JNI Method Descriptors, one of the various string formats used internally by the JVM (and by JNI libraries) for identifying Java elements.
It is difficult to know about what you are talking about. The "method id" can be a reference for a java.lang.reflect.Method object, or can be the method descriptor mentioned below, or any other thing. Where did you read about it?
I doubt there is such table inside the JVM. I mean, I doubt there is a global table, because almost always you retrieve a method from a class, even when dealing with it inside the JVM, so it is reasonable to believe the method is stored in the class. It is likewhen we use reflection to retrieve a method:
Class clazz = String.class;
Method method = clazz.getDeclaredMethod("charAt", Integer.TYPE);
System.out.println(method.getName());
Note that I ask the class String for the method, instead of asking some util class to give me the method charAt, which receives an int and is from the class String.
In other words, your identification tuple is almost correct - it just does not have a class:
(methodName, methodParameters)
and, instead of retrieving the method from the JVM passing the class and then the method name and then the parameter types, you retrieve the method directly from the class, giving the class the method name and the parameter types. A subtle difference, for sure, but I think it is what you are wondering about.
This is evident even in the JNI descriptors I mentioned below. For example, the method
long f(int i, Class c);
is represented by the following descriptor:
"(ILjava/lang/Class;)J"
Note that there is no reference to the class of the method.
The excellent documentation on the class file format (already pointed by #Lawence) may give you some insights. I recommend you to read it fully.
1) How to identify a method more efficiently internally?
Internally to what? There are many places where a method might need to be "identified" "internally". In the bytecode compiler, the JIT compiler, the classloader / linker, the classfile representation, reflection API, a debugger and so on. They each have different efficiency concerns.
2) I heard of "method id". Does it mean there is a mapping between the above triple and an integer, so JVM use only method id after parsing?
A method id is used in the classfile representation, and could be used by anything based on that, including the class loader / linker, the JIT compiler and the debugger.
The JVM doesn't parse Java code.
3) If so, is it resided in symbol table?
It might do. It depends on what you mean by "the symbol table". Bear in mind that there are lots of places where method identification is required, throughout the lifecycle of a class. For instance, the Java reflection APIs require method information to implement methods such as getDeclaredMethod(...) and various methods of Method.
Java always differentiate its language elements by their fully qualified names.
Suppose you have a method myMethod(int a, int b) in class MyClass which lies in the package com.mypackage then java will identify the method with the name com.mypackage.MyClass.myMethod(int a , int b).
Just to give you some more insight, it also takes the Class Loader into consideration when there is a need to resolve two identical elements.
It does consider, which class loader was used to load the particular class containing the method to which you are referring. There are four types of class loaders in java. You can read the documention for java.lang.Thread class for this.

How is Java inheritance being used to enforce program requirements?

I was looking at a blog about good API design link text
In one of the example sections titled 'Reinventing the Socket', it showed a design of how to enforce certain rules and prerequisite on the client code that uses it. eg. the client must call bind() before it can call connect(), and it must be connected before it's allowed to send() or receive() data.
I'm more familiar with C/C++ so I'm having some trouble fully comprehending how the class design is enforcing the API rules. Like for example, how do you prevent client code from making calls into this API with something like this:
SocketConnected s = socket.bind(localaddress, 1000);
//client doesn't call the connect() method
//and just calls the send() method right away.
//this line should give compile-time error
//because only bind() was called but not connect()
s.send(/* some data goes here */);
How and why would the compiler catch that error? If I'm understanding the subclass inheritance correctly, SocketConnected is-a SocketBound which is-a Socket. But if the client code is able to declare a SocketConnected object, how can you enforce the rule that bind() and connect() must be called before send() and receive() are allowed?
Thanks
You enforce the rules by only providing bind() as creator, and no public constructor on SocketConnected. There's no other way of instantiating a SocketConnected except through the API. Yes, you can declare an object of that class, but you cannot create one by yourself; hence you cannot call any instance methods until the proper creator has been called.
ADDED: Re your comment on bind().connect(): that's just an example of chaining, somewhat like a fluent interface, but with type restrictions controlling the order of calls. Think about what happens. The first bind() call creates an instance, on which you then can call connect(). The final code example the likned author provides is a contrast: that's what things would look like with a traditional Berkeley style socket library, where the s is a socket on which both bind() and connect() are possible to call, in any order, without the compiler complaining.
ADDED: Re design pattern - I don't think this has been named. It probably should be. It supports a variation of the design criterion of fail fast, by failing as early as at the compiler stage.
The point is that he's creating interfaces that are defined only to return bound sockets. You get a provider that is only defined to return bound/connected sockets.
if you have an instance of his SocketBound
public interface SocketBound {
SocketConnected connect(Address<?> address, int port);
}
You can only get a SocketConnected from it.

Obj-c delegate model - in Java?

I'm writing a small chat program in Java. I got some classes whose objects have to keep track of one another (e.g. the connection listener needs to update the GUI when a new message comes in, just like the GUI needs to write to the connection's writer, when the user wants to send a message).
In Cocoa on Mac OS X I'd write & implement a delegate model. What about in Java? (So far, I'm just passing 'this' as an argument when I initialize a new object, in order to keep a reference to it from the new object.)
In Cocoa/Objective-C, delegates are objects that adhere to a specified protocol. A Java interface is analogous to an Objective-C protocol, except that Java does not permit optional methods: if your class implements an interface, you must implement all of the methods.
If you're cool with all of a delegate's methods being required, simply define an interface and use that.
If your delegate interface has a lot of methods and it would be convenient to make some of them optional, you could define an Adapter class that implements the delegate interface, providing a default implementation for each of the methods. To use it, your delegate class must either extend the adapter class or, if that is not possible, define a private inner class that extends the adapter class. (Look at Java's MouseListener interface and MouseAdapter class for an example of this.)
In summary, you can still use the delegate pattern in Java, although the static type checking will make optional methods a little more work.
Delegates are not directly provided by the Java language; using a listener pattern is the closest that standard Java comes to delegates.
However, I have implemented callback/delegate support in Java using reflection. Details and working source are available on my website.
How It Works
We have a principle class named Callback with a nested class named WithParms. The API which needs the callback will take a Callback object as a parameter and, if neccessary, create a Callback.WithParms as a method variable. Since a great many of the applications of this object will be recursive, this works very cleanly.
With performance still a high priority to me, I didn't want to be required to create a throwaway object array to hold the parameters for every invocation - after all in a large data structure there could be thousands of elements, and in a message processing scenario we could end up processing thousands of data structures a second.
In order to be threadsafe the parameter array needs to exist uniquely for each invocation of the API method, and for efficiency the same one should be used for every invocation of the callback; I needed a second object which would be cheap to create in order to bind the callback with a parameter array for invocation. But, in some scenarios, the invoker would already have a the parameter array for other reasons. For these two reasons, the parameter array did not belong in the Callback object. Also the choice of invocation (passing the parameters as an array or as individual objects) belongs in the hands of the API using the callback enabling it to use whichever invocation is best suited to it's inner workings.
The WithParms nested class, then, is optional and serves two purposes, it contains the parameter object array needed for the callback invocations, and it provides 10 overloaded invoke() methods (with from 1 to 10 parameters) which load the parameter array and then invoke the callback target.

Categories