Recently I started working on netflix hystrix library. I created a HystrixCommand object but I get a NPE. Ideally, it shouldn't happen. Any help will be appreciated. Is it a known issue ?
Please find the stack trace :
Exception in thread "main" java.lang.NullPointerException
at com.netflix.config.ConcurrentMapConfiguration.clearConfigurationListeners(ConcurrentMapConfiguration.java:330)
at org.apache.commons.configuration.event.EventSource.<init>(EventSource.java:76)
at org.apache.commons.configuration.AbstractConfiguration.<init>(AbstractConfiguration.java:63)
at com.netflix.config.ConcurrentMapConfiguration.<init>(ConcurrentMapConfiguration.java:68)
at com.netflix.config.ConcurrentCompositeConfiguration.<init>(ConcurrentCompositeConfiguration.java:172)
at com.netflix.config.ConfigurationManager.getConfigInstance(ConfigurationManager.java:125)
at com.netflix.config.DynamicPropertyFactory.getInstance(DynamicPropertyFactory.java:263)
at com.netflix.config.DynamicProperty.getInstance(DynamicProperty.java:245)
at com.netflix.config.PropertyWrapper.<init>(PropertyWrapper.java:58)
at com.netflix.hystrix.strategy.properties.archaius.HystrixDynamicPropertiesArchaius$ArchaiusDynamicProperty.<init>(HystrixDynamicPropertiesArchaius.java:62)
at com.netflix.hystrix.strategy.properties.archaius.HystrixDynamicPropertiesArchaius$StringDynamicProperty.<init>(HystrixDynamicPropertiesArchaius.java:73)
at com.netflix.hystrix.strategy.properties.archaius.HystrixDynamicPropertiesArchaius.getString(HystrixDynamicPropertiesArchaius.java:34)
at com.netflix.hystrix.strategy.HystrixPlugins.getPluginImplementationViaProperties(HystrixPlugins.java:344)
at com.netflix.hystrix.strategy.HystrixPlugins.getPluginImplementation(HystrixPlugins.java:334)
at com.netflix.hystrix.strategy.HystrixPlugins.getPropertiesStrategy(HystrixPlugins.java:243)
at com.netflix.hystrix.strategy.properties.HystrixPropertiesFactory.getCommandProperties(HystrixPropertiesFactory.java:62)
at com.netflix.hystrix.AbstractCommand.initCommandProperties(AbstractCommand.java:204)
at com.netflix.hystrix.AbstractCommand.<init>(AbstractCommand.java:163)
at com.netflix.hystrix.HystrixCommand.<init>(HystrixCommand.java:61)
I faced similar issue, and here is how I solved it.
Hystrix -> uses archaius-core-0.4.1.jar -> which uses commons-configuration-1.8.jar
But due to jar conflicts in my current project, commons-configuration-1.3.jar is present instead of commons-configuration-1.8.jar
Unfortunately, there seems to be a bug in commons-configuration-1.3.jar in the constructor of org.apache.commons.configuration.event.EventSource (which I will explain below)
So, my suggestion is take a look into your classpath and I am sure you will find commons-configuration-1.3.jar. If so, just make sure you have the correct commons-configuration-1.8.jar. This should solve your problem!
Root Cause:
com.netflix.config.ConcurrentMapConfiguration -> is a sub class of
org.apache.commons.configuration.AbstractConfiguration -> which is a sub class of org.apache.commons.configuration.event.EventSource
Here is the skeleton
public class ConcurrentMapConfiguration extends AbstractConfiguration {
...
private Collection<ConfigurationListener> listeners = new CopyOnWriteArrayList<ConfigurationListener>();
...
public ConcurrentMapConfiguration() {
...
}
...
#Override
public void clearConfigurationListeners() {
listeners.clear(); // Here is the null pointer exception
}
...
}
But in EventSource (commons-configuration-1.3.jar)
public class EventSource {
...
public EventSource()
{
clearConfigurationListeners(); // This is the culprit
}
...
public void clearConfigurationListeners()
{
listeners = new LinkedList();
}
...
}
As you clearly see in the constructor of EventSource, you see an invocation to method clearConfigurationListeners(). And this method has been overriden in subclass ConcurrentMapConfiguration. So, the subclass method will be invoked. But by this time listeners is still null, because only after super class constructor is done the subclass can start initializing its stuff. Hence the NPE.
But in EventSource (commons-configuration-1.4.jar and above) - it is fixed
public class EventSource {
...
public EventSource()
{
initListeners(); // this is good
}
...
private void initListeners() // private method... Much better! No one can override this :)
{
listeners = new LinkedList();
...
}
...
}
Hope this helps!
Related
I decided to split the last part of that question here into a new question here: https://softwareengineering.stackexchange.com/questions/411738/extension-of-classes-where-to-put-behaviour-how-much-direct-access-is-allowe
If i have a lib and i want to use it, i wrote mostly a own class. This class has one method. In that there is the code how to instantiate the lib/framework. Sometimes there are a few more methods, with them i not only instantiate the class but use it. For example if i want to start a http-server i have there a start-method.
class Container
{
TheLib theLib;
public void init() //or a constructor
{
//some init of the theLib
}
public void start() //
{
theLib.doSomething(...)
theLib.doSomethingmore(...);
theLib.start(...);
}
//important!
public TheLib getTheLib()
{
return this.theLib; //after i started configured it and so on, i want of course use all methods,
which the lib have in some other parts in my application
}
}
But it seems not to be the best solution.
Are there any better solutions, that OO is?
Often i also use only one method, a own class for this seems to be here a big overhead?
Exposing the lib breaks encapsulation? Tell-Dont-Ask is also violated?
Everything depend on what you actually need or how you have access to your 'the lib' instance.
public class Container {
private TheLib theLib;
/* #1: Do you already created the instance before? */
public Container(TheLib theLib) {
this.theLib = theLib;
}
/* #2: Do you need to created the instance each time? */
public Container() {
this.theLib = new TheLib();
}
public void start() {
theLib.doSomething(...)
theLib.doSomethingmore(...);
theLib.start(...);
}
public TheLib getTheLib() {
return this.theLib;
}
public static void main(String[] args) {
/* #1 */
TheLib theLib = ...;
Container container = new Container(theLib);
/* #2 */
Container container = new Container();
/* Continue the flow of your program */
container.start();
container.getTheLib().doSomethingEvenMore();
}
}
Or maybe you actually need only one instance of your 'Container' class. In this case, you should look on how to make a singleton: Java Singleton and Synchronization
Anwser: Often i also use only one method, a own class for this seems to be here a big overhead?
Well, in Java, you cannot do formal programming like in C, so everything line of code that you write, or will be using, has to be in a class of some sort.
If your piece of code is small and don't really need an object, static function might do the work.
just trying out things in java, found following issue.
DefaultAndStaticMethodMain.java:8: error: not a statement
implementation1::sendNotification;
^
1 error
Following is my code.
ParentInterface:
public interface ParentInterface {
default void callForCompletion() {
System.out.println("<<<< Notification sending completed. >>>>");
}
}
Child interface:
public interface ChildInterface extends ParentInterface {
public abstract void sendNotification();
static String printNotificationSentMessage() {
return "Notification is sent successfully.";
}
}
Implementation 1:
public class Implementation1 implements ChildInterface {
#Override
public void sendNotification() {
System.out.println("Implementation --- 1");
System.out.println("Sending notification via email >>>");
}
}
Implementation 2:
public class Implementation2 implements ChildInterface {
#Override
public void sendNotification() {
System.out.println("Implementation ---- 2.");
System.out.println("Sending notification via SMS >>>");
}
}
Main method:
public class DefaultAndStaticMethodMain {
public static void main(String[] args) {
Implementation1 implementation1 = new Implementation1();
implementation1::sendNotification; // Compilation error as shown above.
Implementation2 implementation2 = new Implementation2();
implementation2.sendNotification();
// Following works fine.
// Arrays.asList(implementation1, implementation2).stream().forEach(SomeInterfaceToBeRenamed::sendNotification);
}
}
I am not sure what am I doing wrong, I have JDK 13 installed in local machine and working with IntelliJ 2019.3 with JDK 11. I checked that IntelliJ supports JDK 13
Thanks.
Update
By mistake I left a semi-colon over there, removed it, please check again.
A method reference is not the same as a method call. Those are two distinct things.
A method call is a standalone expression, or, more precisely, an expression statement. That means that in your case implementation2.sendNotification() works, as you would expect.
A method reference, however,
is used to refer to the invocation of a method without actually performing the invocation
and is not a standalone expression. It can only be used where a lambda expression can also be used. A method reference as a standalone expression does not compile, just like an arithmetic expression without assignment (e.g. 3 + 17;). This is enforced by the Java Language Specification, § 14.8 and § 15.13.
More to read:
Please Explain Java 8 Method Reference to instance Method using class name
Method reference in Java 8
What do you intend for the implementation1::sendNotification; line to do? Judging by the implementation2.sendNotification(); line below it looks like you're trying to call sendNotification on implementation1, which is written like this:
implementation1.sendNotification();
The :: notation is a method reference, and (as the error message says) it an identifier, not a statement, and thus can't be a line on its own. Similarly you couldn't write implementation1; (a variable) or ChildInterface; (a class identifier) as a statement.
The .forEach(SomeInterfaceToBeRenamed::sendNotification); line compiles because you are passing the method reference to forEach(), and it in turn invokes each sendNotification() method.
So it seems the following pattern in a class called ActivityClass:
private static class AsyncTaskLoader1 extends AsyncTaskLoader<E> {
........
}
private static class AsyncTaskLoader2 extends AsyncTaskLoader<F> {
.........
}
private class LoaderManager1 extends LoaderManager.LoaderCallbacks<E> {
private void onLoadFinished(AsyncTaskLoader1 loader, E data) {
//do stuff with data
//ok, now we need to start a asynchronous data load based on info we got back from 1st
ActivityClass.this.getLoaderManager().init(0, null, new LoaderManager2()).forceLoad();
}
}
private class LoaderManager2 extends LoaderManager.LoaderCallbacks<D> {
//...
}
This leads to the following runtime exception that looks something like:
java.lang.ClassCastException: E cannot be cast to F
at com.mycompany.myapp.ActivityClass$LoaderManager2.onLoadFinished
I assume this is because I am calling a second loader from the first one. If this is not possible, I assume there is a way to let the Activity know that data has been loaded so it can start a new AsyncTaskLoader from the UI thread, but I don't know how to do that. Could somebody enlighten me? Thanks.
So the issue ended up being that I was passing the same integer ID argument to initLoader for both the original call, AND the one in the first LoadManager's onLoadFinished method. I assume this was resulting in the result of the first loader to be returned to the wrong manager.
I have a following problem with an innner class. Here's the code:
public class PGZUserManagerBean {
// joomla login as separate thread
private class JoomlaLogin extends Thread {
private AuthJoomla authJoomla;
public JoomlaLogin(AuthJoomla authJoomla){
this.authJoomla = authJoomla;
}
#Override
public void run(){
this.authJoomla.authJoomla();
}
}
public void validateuser(){
AuthJoomla authJoomla = new AuthJoomla();
JoomlaLogin joomlaLogin = new JoomlaLogin(authJoomla);
joomlaLogin.start();
}
}
I'm getting java.lang.ClassNotFoundException: PGZUserManagerBean$JoomlaLogin on runtime. I'm using Java 1.6.
Thank you for the help in advance.
al
I strongly suspect that you've copied the class files from one place to another (or put them in a jar file) but you've failed to copy/include PGZUserManagerBean$JoomlaLogin.class.
Check where you're running the code, and look for the class file that the JVM can't find. It will definitely be in your compilation output.
While simple, interface-driven event notification frameworks in Java have been around since pre-Cambrian times (e.g. java.beans.PropertyChangeSupport), it is becoming increasingly popular for frameworks to use annotation-driven event notification instead.
For an example, see JBossCache 2.2. The listener class has its listener methods annotated, rather than conforming to a rigid interface. This is rather easier to program to, and easier to read, since you don't have to write empty implementations of listener callbacks that you're not interested in (and yes, I know about listener adapter superclasses).
Here's a sample from the JBossCache docs:
#CacheListener
public class MyListener {
#CacheStarted
#CacheStopped
public void cacheStartStopEvent(Event e) {
switch (e.getType()) {
case Event.Type.CACHE_STARTED:
System.out.println("Cache has started");
break;
case Event.Type.CACHE_STOPPED:
System.out.println("Cache has stopped");
break;
}
}
#NodeCreated
#NodeRemoved
#NodeVisited
#NodeModified
#NodeMoved
public void logNodeEvent(NodeEvent ne) {
log("An event on node " + ne.getFqn() + " has occured");
}
}
The problem with this, is that it's very much more of an involved process writing the framework to support this sort of thing, due to the annotation-reflection nature of it.
So, before I charge off down the road of writing a generic framework, I was hoping someone had done it already. Has anyone come across such a thing?
You can already do this today with EventBus.
Following example is from EventBus Getting Started guide. Statusbar that updates based on published events, and no need to register statusbar control/widget as listener of publisher(s). Without EventBus, statusbar will need to be added as listener to many classes. Statusbar can also be created and destroyed at any time.
public StatusBar extends JLabel {
public StatusBar() {
AnnotationProcessor.process(this);
}
#EventSubscriber(eventClass=StatusEvent.class)
public void updateStatus(StatusEvent statusEvent) {
this.setText(statusEvent.getStatusText();
}
}
A similar project is ELF (Event Listener Framework) but it seems to be less mature.
I'm currently researching about event notification frameworks on Publish-Subscribe Event Driven Programming | Kev's Spring vs Java EE Dev and the followup articles.
I've made http://neoevents.googlecode.com to handle this kind of annotation based event handler.
#actionPerformed
private void onClick() {
//do something
}
protected void initComponents() {
JButton button = new JButton("Click me!!!");
button.addActionListener(new ActionListener(this) );
}
It looks as simple as I was expecting it to be. Annotations are available for every single listener in J2SE.
Don't mistake complicated for clever. It seems to me that this would be:
A nightmare to debug
Difficult to follow (from a maintenance perspective, or someone attempting to change something 6 months down the line)
Full of if (event instanceof NodeCreatedEvent) like code. Why this is better than subclassing an adapter I have no idea!
The main problem I see here are the method parameters, which restrict which methods can actually be used for which events, and there's no compile-time help for that.
This is what makes interfaces attractive to me for observer pattern implementations like the Java event model. Tools like eclipse can autogen method stubs so you can't get the signatures wrong. In your example, it's very easy to use the wrong parameter type and never know it until an event occurs (which might be an error case several months down the line)
One thing you might try are my annotations & processor for implementing observers and null object implementations. Suppose you have
package a.b.c;
public interface SomeListener {
void fee();
void fie();
void fo();
void fum();
}
and wanted to create a listener instance. You could write
package x.y.z;
import a.b.c.SomeListener;
import com.javadude.annotation.Bean;
import com.javadude.annotation.NullObject;
#Bean(nullObjectImplementations = {#NullObject(type = SomeListener.class) })
public class Foo extends FooGen implements SomeListener {
#Override
public void fie() {
// whatever code you need here
}
}
To create a source for these events, you can write
package a.b.c;
import com.javadude.annotation.Bean;
import com.javadude.annotation.Observer;
#Bean(observers = {#Observer(type = SomeListener.class)})
public class Source extends SourceGen {
// SourceGen will have add/remove listener and fire methods
// for each method in SomeListener
}
See http://code.google.com/p/javadude/wiki/Annotations if you're interested. Might give you some other ideas as well.
Google Guava v11 has added an EventBus component that uses this style. They also explain why they decided to use annotations rather than interfaces.
I've been thinking about a generic annotation-driven event framework as well. I like the benefits provided by static typing, but the current interface-driven event model is painful to use (ugly code). Would it be possible to use a custom annotation processor to do some compile-time checking? That might help add some of the missing "safety" that we've all grown used to.
A lot of the error checking can also be done at the time that the listeners are "registered" with the event producers. Thus, the application would fail early (when the listeners are registered), possibly even at at startup-time.
Here's an example of what the generic framework I've been toying with might look like:
public class ExampleProducer {
private EventSupport<ActionEvent> eventSupport;
public ExampleProducer() {
eventSupport = new EventSupport<ActionEvent>(this);
}
#AddListenersFor(ActionEvent.class)
public void addActionListener(Object listener)
{
eventSupport.addListener(listener);
}
#RemoveListenersFor(ActionEvent.class)
public void removeActionListener(Object listener)
{
eventSupport.removeListener(listener);
}
public void buttonClicked() {
eventSupport.fire(new ActionEvent(this,
ActionEvent.ACTION_PERFORMED, "Click"));
}
}
The producer uses EventSupport, which uses reflection to invoke the events. As mentioned before, EventSupport could preform some initial checks when the events listeners are registered.
public class ExampleListener
{
private ExampleProducer submitButton;
public ExampleListener()
{
submitButton = new ExampleProducer();
EventSupport.autoRegisterEvents(this);
}
#HandlesEventFor("submitButton")
public void handleSubmitButtonClick(ActionEvent event)
{
//...some code to handle the event here
}
}
Here, EventSupport has a static method that uses reflection to auto-register the listener with the event producer. This eliminates the need to manually register with the event source. A custom annotation processor could be used to validate that the #HandlesEventFor annotation refers to an actual field of the ExampleListener. The annotation processor could do other checks as well, such as ensuring that the event handler method signature matches up with one of the registration methods on the ExampleProducer (basically, the same check that could be performed at registration-time).
What do you think? Is this worth putting some time into fully developing?
Here's a similar project called SJES.
public class SomeController {
private Calculator c1 = new Calculator();
private Calculator c2 = new Calculator();
public SomeController() {
c1.registerReceiver(this);
c2.registerReceiver(this);
c1.add(10, 10);
c2.add(20, 20);
}
#EventReceiver(handleFor="c1")
public void onResultC1(Calculator.Event e) {
System.out.println("Calculator 1 got: " + e.result);
}
#EventReceiver(handleFor="c2")
public void onResultC2(Calculator.Event e) {
System.out.println("Calculator 2 got: " + e.result);
}
#EventReceiver
public void onResultAll(Calculator.Event e) {
System.out.println("Calculator got: " + e.result);
}
}
public class Calculator {
private EventHelper eventHelper = new EventHelper(this);
public class Event {
long result;
public Event(long result) {
this.result = result;
}
}
public class AddEvent extends Event {
public AddEvent(long result) {
super(result);
}
}
public class SubEvent extends Event {
public SubEvent(long result) {
super(result);
}
}
public void unregisterReceiver(Object o) {
eventHelper.unregisterReceiver(o);
}
public void registerReceiver(Object o) {
eventHelper.registerReceiver(o);
}
public void add(long a, long b) {
eventHelper.fireEvent(new AddEvent(a + b));
}
public void sub(long a, long b) {
eventHelper.fireEvent(new SubEvent(a - b));
}
public void pass(long a) {
eventHelper.fireEvent(new Event(a));
}
}
I think this is very easy to use.
You can also check out MBassador It is annotation driven, very light-weight and uses weak references (thus easy to integrate in environments where objects lifecycle management is done by a framework like spring or guice or somethign).
It provides an object filtering mechanism (thus you could subscribe to NodeEvent and attach some filters to restrict message handling to a set of specific types only).
You can also define your own annotations to have customized declaration of your handlers.
And it's very fast and resource efficient. Check out this benchmark showing a performance graph for different scenarios using Guava or mbassador.