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.
Related
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.
Effective Java 3rd Edition, Item 18: Favor composition over inheritance describes an issue with using inheritance to add behavior to a class:
A related cause of fragility in subclasses is that their superclass can acquire new methods in subsequent releases. Suppose a program depends for its security on the fact that all elements inserted into some collection satisfy some predicate. This can be guaranteed by subclassing the collection and overriding each method capable of adding an element to ensure that the predicate is satisfied before adding the element. This works fine until a new method capable of inserting an element is added to the superclass in a subsequent release. Once this happens, it becomes possible to add an "illegal" element merely by invoking the new method, which is not overridden in the subclass.
The recommended solution:
Instead of extending an existing class, give your new class a private field that references an instance of the existing class... Each instance method in the new class invokes the corresponding method on the contained instance of the existing class and returns the results. This is known as forwarding, and the methods in the new class are known as forwarding methods... adding new methods to the existing class will have no impact on the new class... It's tedious to write forwarding methods, but you have to write the reusable forwarding class for each interface only once, and forwarding classes may be provided for you. For example, Guava provides forwarding classes for all of the collection interfaces.
My question is, doesn't the risk remain that methods could also be added to the forwarding class, thereby breaking the invariants of the subclass? How could an external library like Guava ever incorporate newer methods in forwarding classes without risking the integrity of its clients?
The tacit assumption seems to be that you are the one writing the forwarding class, therefore you are in control of whether anything gets added to it. That's the common way of using composition over inheritance, anyway.
The Guava example seems to refer to the Forwarding Decorators, which are explicitly designed to be inherited from. But they are just helpers to make it simpler to create these forwarding classes without having to define every method in the interface; they explicitly don't shield you from any methods being added in the future that you might need to override as well:
Remember, by default, all methods forward directly to the delegate, so overriding ForwardingMap.put will not change the behavior of ForwardingMap.putAll. Be careful to override every method whose behavior must be changed, and make sure that your decorated collection satisfies its contract.
So, if I understood all this correctly, Guava is not such a great example.
doesn't the risk remain that methods could also be added to the forwarding class, thereby breaking the invariants of the subclass?
Composition is an alternative to inheritance, so when you use composition, there is no sub-class. If you add new public methods to the forwarding class (which may access methods of the contained instance), that means you want these methods to be used.
Because you are the owner of the forwarding class, only you can add new methods to it, thus maintaining the invariant.
Why should one use a "Dynamic Proxy class" instead of the "standard proxy" pattern?
What are the disadvantages or advantages of both?
It seems like they both have the same end result, except that they are implemented differently.
Dynamic proxy class
https://docs.oracle.com/javase/8/docs/technotes/guides/reflection/proxy.html
A dynamic proxy class is a class that implements a list of interfaces
specified at runtime such that a method invocation through one of the
interfaces on an instance of the class will be encoded and dispatched
to another object through a uniform interface. Thus, a dynamic proxy
class can be used to create a type-safe proxy object for a list of
interfaces without requiring pre-generation of the proxy class, such
as with compile-time tools. Method invocations on an instance of a
dynamic proxy class are dispatched to a single method in the
instance's invocation handler, and they are encoded with a
java.lang.reflect.Method object identifying the method that was
invoked and an array of type Object containing the arguments.
Standard proxy pattern https://en.wikipedia.org/wiki/Proxy_pattern
A proxy, in its most general form, is a class functioning as an
interface to something else. The proxy could interface to anything: a
network connection, a large object in memory, a file, or some other
resource that is expensive or impossible to duplicate. In short, a
proxy is a wrapper or agent object that is being called by the client
to access the real serving object behind the scenes. In the proxy
extra functionality can be provided, for example caching when
operations on the real object are resource intensive, or checking
preconditions before operations on the real object are invoked. For
the client, usage of a proxy object is similar to using the real
object, because both implement the same interface.
You have appeared to answer your own question. You should use the one which is easier to implement for your use case.
You need to dynamic proxy when you do not have an implementation for each method at compile time.
For example, mocking test libraries use the dynamic proxies so that can write code to handle any method generically.
Serialization makes sense as an instance method - an object might reasonably be able to serialize itself. An object should only ever be in a valid state, and all valid states of an object should be permissible to serialize. There is nothing invalid about this idea.
But deserialization does not make sense as an instance method. No part of an object's state should have any bearing on the process of constructing another object from data. There is no class foo such that you need a constructed foo in order to construct a foo.
So my question is, does standard java have a pre-existing set of interfaces/facilities to facilitate static deserialization? If you implement the instance-based approach, your deserialization "just works" (as much as anything does) with anything that works with Java's default deserialization ability.
Is there anything built in, to use classes as factories for objects of that class, constructed from serial data? Is there anything in Java I could pass a class to, such that this facility would know to call some static method to deserialize to construct an object from its flat form?
The deserialization instance method readObject is private. There is no way to call it from the outside. You could call it from one of your instance methods, but that would be very strange and I'd question why you'd be doing that in the first place. You say:
No part of an object's state should have any bearing on the process of constructing another object from data.
True, but I don't see why you think this would be an issue. There's no way you could call readObject from the outside (unless you call it from some other public method, which as I said, is kind of iffy) on an instance that you have already created. When you deserialize, you will most probably be using ObjectInputStream, which will use the no-args constructor to create a new instance, and then will hydrate that object using the data from the stream (when you call ObjectInputStream#readObject). So there is no question of the state of the instance affecting deserialization, because what you get back is an instance created from the serialized data (as Object, but you will then cast it to the concrete type).
In effect, readObject behaves somewhat like a constructor, except that it uses previously-serialized data to create an instance of an object. Extending the analogy, your question wouldn't make sense because you would be asking "Why does creating an object using the constructor have anything to do with the state of the instance?". The question of state doesn't even apply because you don't even have an instance! Similarly, state doesn't come into play with readObject because can never* deserialize and create an instance by using an existing instance.
If you want greater control over serialization, you can override readObject and writeObject from Serializable within your class if you want to handle things in a special way. You can exert greater control over how the data is written out by implementing Externizable and providing implementations for readExternal and writeExternal.
In your second question you're wondering what the "something" is that calls readObject. The "something" is reflection; ObjectInputStream will check to see if the class has a readObject method. If you've provided your own implementation, it will call that. Otherwise it will call defaultReadObject (which contains the logic for default serialization).
As far as built-in factories for deserialization, there isn't anything and I haven't really felt a need something since the standard serialization/deserialization approach seems to work well.
If you want more information on this, I suggest taking a look at the serialization specification for a comprehensive and in-depth view of how Java tackles serialization, and specifically Object Input Classes for your particular question.
*The only way state comes into it is if you do something strange like calling the readObject method from some other instance method (which would have to take in an ObjectInputStream), and then you have custom logic that performs deserialization based on the state of the existing instance. In other words, the only way the object's state has any bearing on deserialization logic is if you explicitly write it that way. Again, as I mentioned before, that would be very strange code, with a whole lot of caveats and of minimal value.
I have already read the interesting discussion on following SO thread about ThreadLocal and its use.
When and how should I use a ThreadLocal variable?
Purpose of ThreadLocal?
How does ThreadLocal usage reduce reusability
Is it OK to use ThreadLocal for storing the requested Locale?
This questions is more towards a design time choice. My scenario is like this
If I have a value object in a web application that may need to used inside same thread by almost all steps. I can think of two interface design options like below
Approach #1 Using Method Parameter Passing.
I have so far focused on coming up with a interface that can have methods with parameters of a value object interface.
For example:
public interface SomeDataProcessorInterface {
public void processSomething(SomeValueObjectInterface vo);
}
public interface SomeValueObjectInterface extends Serializable {}
Aproach #2 Using ThreadLocal
In this approach I can have a interface with no method parameter and just create a static class to access my value objects using a threadlocal.
For example:
public interface SomeDataProcessorInterface {
public void processSomething();
}
public interface SomeValueObjectInterface extends Serializable {}
public Class StaticClass {
private static ThreadLocal<SomeValueObjectInterface> threadLocalVO = new ThreadLocal<SomeValueObjectInterface>();
public static ThreadLocal getThreadLocal() {
return threadLocal;
}
Which approach is better? and why?
Which one of these implementation is going to have less chances of memory leak?
Which one of these implementation is going to be good for Java Garbage Collector?
I read thru some of the points in other thread however I am still not clear which approach is better if I am starting from scratch.
If you have a choice between passing something as a method parameter or via ThreadLocal storage, you should 99.99999% of the time pass it as a method parameter. The main purpose of ThreadLocal storage is to handle cases where one is calling a method indirectly (meaning one is asking some other method to in turn call the method of interest), one needs to pass information to the inner method, and the method in the middle provides no convenient conduit for passing that information. If there were no "middle layer", one could simply add the additional parameter to the inner method's signature (generally the inner method would only be called by the code which has the information, so adding the parameter at both the method definition and call site should be no problem). In some cases, however, middle layers exist and must be worked with.
For sample, consider a ShapeCollection which includes a DrawAll method which calls Draw on all its shapes. An application defines some shapes which are slow to render "nicely", and thus adds an option to each window to select whether to have such shapes appear as a place-holder rather than a detailed rendering. If Shape had been designed with such needs in mind, its Draw method could have included an asPlaceHolder parameter, and ShapeCollection's DrawAll could have accepted such a parameter and passed it to each shape. If the designer of Shape hasn't anticipated such a need, however, ShapeCollection isn't going to support it.
If each fancy shape objects's Draw method will only be used for the purpose of updating one particular window, the shape could hold a reference to that window, and use that window's "Use placeholders" option in determining how it should render itself. If, however, there could be multiple windows showing views of the shape, and each should support its own rendering options, that approach may not work. Such an approach may also have problems if the Draw method gets used to render things for the clipboard, a printer, or other medium. Having a window's drawing code construct a DrawingOptions object, create a thread-local reference to it, call DrawAll, and then erase that thread-local reference would be inelegant, but it would provide a means for calls to DrawAll to pass drawing options to the inner Draw method--something that would otherwise not be possible.
It is a design issue, and depends on your case.
If SomeValueObjectInterface have meaning in the context of service's business logic, then (I believe) it shall be a parameter, but if you consider it as data for crosscutting concerns (aspects which are not implemented as aspects), and it is not a parameter of business logic, then use ThreadLocal.
By the way don't forget to clear the ThreadLocal in a finally block, or you would encounter memory-leak issues (which are mostly hard to find).
And there is no difference for GC, because if you don't forget to clear the ThreadLocal then the objects in both approaches would be in eden.
With static TheadLocals you risk leaking memory if you forget to remove the element. You can always avoid this by removing the element before returning from your method. I wouldn't recommend this approach.
Your 1st approach is already thread safe, as it stands, since the parameter will be local to that method call only. Use this one.