I'm trying to figure out how to listen to a property change in another class. Below is my code:
ClassWithProperty has the property I want to listen to:
public class ClassWithProperty {
private PropertyChangeSupport changes = new PropertyChangeSupport(this);
private int usersOnline;
public int getUsersOnline() {
return usersOnline;
}
public ClassWithProperty() {
usersOnline = 0;
while (usersOnline<10) {
changes.firePropertyChange("usersOnline", usersOnline, usersOnline++);
}
}
public void addPropertyChangeListener(
PropertyChangeListener l) {
changes.addPropertyChangeListener(l);
}
public void removePropertyChangeListener(
PropertyChangeListener l) {
changes.removePropertyChangeListener(l);
}
}
Main is where i need to know about the property change:
public class Main {
private static ClassWithProperty test;
public static void main(String[] args) {
test = new ClassWithProperty();
test.addPropertyChangeListener(listen());
}
private static PropertyChangeListener listen() {
System.out.println(test.getUsersOnline());
return null;
}
}
I have the event fired only the last time (usersOnline=10).
I'm new to Java and tried to find a solution, but to no avail.
The code:
private static PropertyChangeListener listen() {
System.out.println(test.getUsersOnline());
return null;
}
returns null which means "no object", which in turn means that test.addPropertyChangeListener(listen()) is effectively test.addPropertyChangeListener(null), which won't register anything.
You must pass a valid instance of a PropertyChangeListener to the addPropertyChangeListener() method.
Edit
I suggest you read the Java tutorial's chapter about PropertyChangeListeners:
http://download.oracle.com/javase/tutorial/uiswing/events/propertychangelistener.html
Another problem of your code is that you call firePropertyChange() in the constructor of ClassWithProperty. But at that time, no listener can possibly be registered, so it does not have any effect. Any call to addPropertyChangeListener() happens after you have fired the events.
Here is your code modified so that it should work (haven't tested it though...):
public class ClassWithProperty {
private PropertyChangeSupport changes = new PropertyChangeSupport(this);
private int usersOnline = 0;
public ClassWithProperty() {
}
public void setupOnlineUsers()
{
while (usersOnline < 10) {
changes.firePropertyChange("usersOnline", usersOnline, ++usersOnline);
}
}
public int getUsersOnline() {
return usersOnline;
}
public void addPropertyChangeListener(PropertyChangeListener l) {
changes.addPropertyChangeListener(l);
}
public void removePropertyChangeListener(PropertyChangeListener l) {
changes.removePropertyChangeListener(l);
}
}
public class MainListener implements PropertyChangeListener {
private ClassWithProperty test;
public MainListener() {
test = new ClassWithProperty();
test.addPropertyChangeListener(this);
test.setupOnlineUsers();
}
public void propertyChange(PropertyChangeEvent evt) {
System.out.println(test.getUsersOnline());
}
public static void main(String[] args) {
new MainListener(); // do everything in the constructor
}
}
What I do is put a method in the ClassWithProperty class:
public PropertyChangeSupport getPropertyChangeSupport() {
return changes;
}
Then, register for property change events in the constructor of your Main() class:
private void initializeListeners() {
test.getPropertyChangeSupport().addPropertyChangeListener((PropertyChangeEvent event) -> {
if (event.getPropertyName().equals("usersOnline")) {
String passedEventData = (String) event.getNewData();
}
});
}
This make it so you are not repeating the code in your ClassWithProperty with methods that are already in the PropertyChangeSupport class.
when you need to fire an event in your ClassWithProperty class, do:
changes.firePropertyChange("usersOnline", oldValue, newValue);
One notable feature of this method is that, if the
event.getOldValue() and the event.getNewValue()
are equal, the event will not fire. If you want to fire repeated events with the same information, use null in the oldValue field;
The firePropertyChange() method only passes int, boolean and Object. So if you are not passing an int or boolean, you need to cast the value that was passed in the event on the receiving end.
Your method here:
public ClassWithProperty() {
usersOnline = 0;
while (usersOnline<10) {
changes.firePropertyChange("usersOnline", usersOnline, usersOnline++);
usersOnline++;
}
}
has a while loop that will continuously loop and block the thread. My limited knowledge of property change listeners is that they listen for changes to a bound property, here the usersOnLine variable, meaning the property change should only fire if this number changes (likely within in any setUserOnLine, addUserOnLine, removeUserOnLine and similar methods). For more on bound properties, please look here: Bound Properties
Related
I ran into a bit of an issue and was hoping someone could tell me what I'm missing here.
for some context I have the following methods:
private boolean windowork;
public class WinidowMalfunction extends Event {
ControllerException newException = new ControllerException("Error:");
public WinidowMalfunction(long delayTime) {
super(delayTime);
}
public void action() throws ControllerException {
windowork = false;
someThingWentWrongHere(1, "Error at WinidowMalfunction");
}
}
private boolean poweron;
public class PowerOut extends Event {
public PowerOut(long delayTime) {
super(delayTime);
}
public void action() throws ControllerException {
poweron = false;
someThingWentWrongHere(2, "Error at powerOut event");
}
}
and I'm creating interface Fixable where I need to change the value of poweron and windowork to change their values to true. but I can't get the FIxable to accept the references. they are all in the same class so is there a way to reference these boolean function in an interface
EDIT:
Assignment question:
In this part, we add functionality for restoring the saved GreenhouseControls object and having it resume execution where it left off. It demonstrates the use of interfaces and the capability of Java methods to return objects.
Create the following interface
interface Fixable {
// turns Power on, fix window and zeros out error codes
void fix ();
// logs to a text file in the current directory called fix.log
// prints to the console, and identify time and nature of
// the fix
void log();
}
You can do something like this:
interface Fixable {
public boolean setTrue();
}
class Foo implements Fixable {
private boolean windowork = false;
public void setTrue() {
windowork = true;
}
}
class Bar implements Fixable {
private boolean poweron = false;
public void setTrue() {
poweron = true;
}
}
The only advantage of the above is if you had an array of Fixable objects you could iterate thru them and do this.
for (Fixable f : fixableArray) {
f.setTrue();
}
An interface can be designed in a way to read-write a boolean property that resides in the class/instance.
public interface Somename {
public boolean isPowerOn();
public void setPowerTo(boolean arg);
}
I have several fragments. One of them can start IntentService for heavy operation. The question is, what it the best way to get progress/status of that background task from another fragments?
If you want something like callback mechanism, you can implement Observer-like architecture/pattern for it.
Read about Observer pattern on wikipedia (with Java samples)
Here is my sample for you:
public class ObservableProgress {
public interface Observer {
void onProgressChanged(Object newProgress);
}
// I do not know the type of your progress
private static volatile Object progress;
private static final List<Observer> observers = new LinkedList<Observer>();
// closing constructor for clear class's api
private ObservableProgress() {}
// on each progress change, all observers would be notified about progress change
public static void setProgress(Object newProgress) {
progress = newProgress;
notifyOnProgressChanged(newProgress);
}
public static Object getProgress() {
return progress;
}
// use it to add progress listener
public static void addObserver(Observer observer) {
observers.add(observer);
}
// use it to remove progress listener
public static void removeObserver(Observer observer) {
observers.remove(observer);
}
private static void notifyOnProgressChanged(Object newProgress) {
for (Observer observer : observers) {
if (observer != null) {
observer.onProgressChanged(newProgress);
}
}
}
}
In your service you should define static variables that change value based on the status. Then you can read those variables from your fragment.
You can have an int that goes from 0 to 100.
Define it like this:
public static int progress = 0;
Read it like this:
int getprogress = JavaClassName.progress;
I am very new to java so sorry in advance if anything I say sounds newbish, be gentle.
I have implemented a basic Observer Pattern. Some observers should only listen to one update and then immediately remove themselves from the observers/listeners list. However, whenever I tried doing that I got the famous java.util.concurrentmodificationexception error.
I'm obviously getting this error because I'm changing the list while still iterating over it, yet I am still unsure what is the right solution. I'm wondering if I'm even doing this the right way. If I am, what would be the needed fix to make it work? And if I'm not, I'd like to get suggestions for a better way of achieving what I'm trying to do.
Here's my code:
public interface Listener {
public void onValueChange(double newValue);
}
public class Observed {
private int value;
List<Listener> listeners = new ArrayList<>();
public void addListener(Listener toAdd) {
listeners.add(toAdd);
}
public void removeListener(Listener toRemove) {
listeners.remove(toRemove);
}
public void changeValue(double newValue) {
value = newValue;
for (Listener l : listeners) l.onValueChange(newValue);
}
}
public class SomeClassA implements Listener{
private Observed observed;
SomeClassA(Observed observed) {
this.observed = observed;
}
#Override
public void onValueChange(double newValue) {
System.out.println(newValue);
observed.removeListener(this);
}
}
public class SomeClassB implements Listener{
#Override
public void onValueChange(double newValue) {
System.out.println(newValue);
}
}
public class ObserverTest {
public static void main(String[] args) {
Observed observed = new Observed();
SomeClassA objectA = new SomeClassA(observed);
SomeClassB objectB = new SomeClassB();
observed.addListener(objectB);
observed.addListener(objectA);
observed.changeValue(4);
}
}
one ways is to go fo CopyOnWriteArraylist instead of ArrayList .
CopyOnWriteArraylist is a thread-safe variant of ArrayList in which
all mutative operations (add, set, and so on) are implemented by
making a fresh copy of the underlying array.
Reason why its thrown in your case
you are modifying a collection directly while it is iterating over the collection under method changeValue()
You can not remove items from a collection while you are iterating over it. That is, unless you use the Iterator#remove method. Since that is not a possibility in this case, an alternative is make a copy of your listener list and iterate over that instead. In that case the original listener list is free to be manipulated by the individual listeners:
public void changeValue(double newValue) {
value = newValue;
List<Listener> copyOfListeners = new ArrayList<Listener>(listeners);
for(Listener l : copyOfListeners) {
l.onValueChange(newValue);
}
}
the code below works, so you can try whatever it does.
import java.util.Observable;
import java.util.Observer;
class Model extends Observable {
public void setX(double x) {
this.x=x;
System.out.println("setting x to "+x);
setChanged();
notifyObservers();
}
double x;
}
class A implements Observer {
A(Model model) {
this.model=model;
}
#Override public void update(Observable arg0,Object arg1) {
System.out.println(getClass().getName()+" "+((Model)arg0).x);
((Model)arg0).deleteObserver(this);
}
Model model;
}
class B implements Observer {
#Override public void update(Observable arg0,Object arg1) {
System.out.println(getClass().getName()+" "+((Model)arg0).x);
}
}
public class So19197579 {
public static void main(String[] arguments) {
Model model=new Model();
model.addObserver(new A(model));
model.addObserver(new B());
model.setX(4);
model.setX(8);
}
}
first of all i am new to threads and shared variables. So please be kind with me ;-)
I'm having a class called Routing. This class recieves and handles messages. If a message is of type A the Routing-Object should pass it to the ASender Object which implements the Runnable Interface. If the message is of type B the Routing-Class should pass it to the BSender Object.
But the ASender and BSender Objects have common variables, that should be stored into the Routing-Object.
My idea now is to declare the variables as synchronized/volatile in the Routing-Object and the getter/setter also.
Is this the right way to synchronize the code? Or is something missing?
Edit: Added the basic code idea.
RoutingClass
public class Routing {
private synchronized Hashtable<Long, HashSet<String>> reverseLookup;
private ASender asender;
private BSender bsender;
public Routing() {
//Constructor work to be done here..
reverseLookup = new Hashtable<Long, HashSet<String>>();
}
public void notify(TopicEvent event) {
if (event.getMessage() instanceof AMessage) {
asender = new ASender(this, event.getMessage())
} else if (event.getMessage() instanceof BMessage) {
bsender = new BSender(this, event.getMessage())
}
}
public synchronized void setReverseLookup(long l, Hashset<String> set) {
reverseLookup.put(l, set);
}
public synchronized Hashtable<Long, Hashset<String>> getReverseLookup() {
return reverseLookup;
}
}
ASender Class
public class ASender implements Runnable {
private Routing routing;
private RoutingMessage routingMessage;
public ASender(Routing r, RoutingMessage rm) {
routing = r;
routingMessage = rm;
this.run();
}
public void run() {
handleMessage();
}
private void handleMessage() {
// do some stuff and extract data from the routing message object
routing.setReverseLookup(somethingToSet)
}
}
Some comments:
Hashtable is a thread-safe implementation, you do not need another "synchronized" keyword see this and this for more information
Avoid coupling, try to work with interfaces or pass the hashtable to your senders, see this for more information
Depending on the amount of senders, you might want to use a ConcurrentHashMap, it greatly improves the performance, see ConcurrentHashMap and Hashtable in Java and Java theory and practice: Concurrent collections classes
This would conclude something like...:
public interface IRoutingHandling {
void writeMessage(Long key, HashSet<String> value);
}
public class Routing implements IRoutingHandling {
private final Hashtable<Long, HashSet<String>> reverseLookup;
private ASender asender;
private BSender bsender;
public Routing() {
//Constructor work to be done here..
reverseLookup = new Hashtable<Long, HashSet<String>>();
}
public void notify(TopicEvent event) {
if (event.getMessage() instanceof AMessage) {
asender = new ASender(this, event.getMessage())
} else if (event.getMessage() instanceof BMessage) {
bsender = new BSender(this, event.getMessage())
}
}
#Override
public void writeMessage(Long key, HashSet<String> value) {
reverseLookup.put(key, value);
}
}
public class ASender implements Runnable {
private IRoutingHandling _routingHandling;
public ASender(IRoutingHandling r, RoutingMessage rm) {
_routingHandling = r;
routingMessage = rm;
this.run();
}
public void run() {
handleMessage();
}
private void handleMessage() {
// do some stuff and extract data from the routing message object
_routingHandling.writeMessage(somethingToSetAsKey, somethingToSetAsValue)
}
}
In my web app, during some change over the object, i need to send a mail about the changes happened in the object.
My question is how to write a listener for this.
Please give me some article regarding this.
Thanks
A typical implementation could be like this: your object is observable. So every time, one of the (observed) values changes, an event is fired and all registered listeners are notified. One of those listeners now would be designed to take the notification and create and send an EMail (Java Mail API)
Let's take a sample bean which we make observable:
public class Bean implements Observable{
// code to maintain listeners
private List<Listener> listeners = new ArrayList<Listener>();
public void add(Listener listener) {listeners.add(listener);}
public void remove(Listener listener) {listeners.remove(listener);}
// a sample field
private int field;
public int getField() {return field;}
public int setField(int value) {
field = value;
fire("field");
}
// notification code
private void fire(String attribute) {
for (Listener listener:listeners) {
fieldChanged(this, attribute);
}
}
}
The Listener interface:
public interface Listener {
public void fieldChanged(Object source, String attrbute);
}
The Observable interface:
public interface Observable {
public void add(Listener listener);
public void remove(Listener listener);
}
And the EMailer:
public class Sender implements Listener {
public void register(Observable observable) {observable.add(this);}
public void unregister(Observable observable) {observable.remove(this);}
public void fieldChanged(Object source, String attribute) {
sendEmail(source, attribute); // this has to be implemented
}
}
EDIT
Corrected an ugly mistake in the setter method - now the event is fired after the property has been set. Was the other way round, with the side effect, that if a listener read the changed property, he still saw the old, unchanged value...
If you simply wish to know about the properties of an object being modified I would recommend using a PropertyChangeListener. That way you can use the PropertyChangeSupport utility class to manage your listener instances and the firing of events. You also avoid reinventing the wheel.
For more bespoke event firing I would recommend defining your own listener interface.
Example Class
public class MyBean {
private final PropertyChangeSupport support;
private int i;
private boolean b;
public MyBean() {
this.support = new PropertyChangeSupport(this);
}
// Accessors and Mutators. Mutating a property causes a PropertyChangeEvent
// to be fired.
public int getI() { return i; }
public void setI(int i) {
int oldI = this.i;
this.i = i;
support.firePropertyChange("i", oldI, this.i);
}
public boolean getB() { return b; }
public void setB(boolean b) {
boolean oldB = this.b;
this.b = b;
support.firePropertyChange("b", oldB, this.b);
}
// Wrapper methods that simply delegate listener management to
// the underlying PropertyChangeSupport class.
public void addPropertyChangeListener(PropertyChangeListener l) {
support.addPropertyChangeListener(l);
}
public void addPropertyChangeListener(String propertyName, PropertyChangeListener l) {
// You would typically call this method rather than addPropertyChangeListener(PropertyChangeListener)
// in order to register your listener with a specific property.
// This then avoids the need for large if-then statements within your listener
// implementation in order to check which property has changed.
if (!"i".equals(propertyName) && !"b".equals(propertyName)) {
throw new IllegalArgumentException("Invalid property name: " + propertyName);
}
support.addPropertyChangeListener(propertyName, l);
}
public void removePropertyChangeListener(PropertyChangeListener l) {
support.removePropertyChangeListener(l);
}
public void removePropertyChangeListener(String propertyName, PropertyChangeListener l) {
support.removePropertyChangeListener(propertyName, l);
}
}
Example Usage
// Create a new instance of our observable MyBean class.
MyBean bean = new MyBean();
// Create a PropertyChangeListener specifically for listening to property "b".
PropertyChangeListener listener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
assert "b".equals(evt.getPropertyName());
boolean oldB = (Boolean) evt.getOldValue();
boolean newB = (Boolean) evt.getNewValue();
System.err.println(String.format("Property b updated: %b -> %b, oldB, newB));
}
}
// Register listener with specific property name. It will only be called back
// if this property changes, *not* the "i" int property.
bean.addPropertyChangeListener("b", listener);
You should use the Observer Design Pattern. This pattern uses these classes :
java.util.Observable
java.util.Observer
Here is an example.
The observer :
public class EmailObserver implements Observer
{
#Override
public void update(Observable obj, Object arg)
{
if (obj instanceof YourObject)
{
// TODO Send the mail or whatever, you have access to the modified object through obj
// In arg you can put some additional parameter, like the modified field
}
}
}
The Observable Object :
public static class YourObject extends Observable
{
public void setSomething(Object parameter)
{
// TODO some modification in YourObject
setChanged(); // From Observable : the object has changed
notifyObservers(parameter); // Notify the observer about the change
}
}
And the main class :
public static void main(String[] args)
{
// Create YourObject
YourObject o = new YourObject();
// create an observer
EmailObserver emailObserver = new EmailObserver();
// subscribe the observer to your object
o.addObserver(emailObserver);
// Now you can modify your object, changes will be notified by email
o.setSomething(...);
}
Use Observer design pattern http://en.wikipedia.org/wiki/Observer_pattern.
http://java-x.blogspot.com/2007/01/implementing-observer-pattern-in-java.html