Removing Listeners in finalize()
I have a Model-View architecture, where I basically load my Model objects once, and then create and destroy my View object frequently as the user uses the application. The View objects register propertyChangeListeners with the Model objects. Now I want to avoid having hundreds of "old" listeners left over from previous View objects, so I was thinking that I put a removePropertyChangeListener call in the finalize() method of my View objects. Having left over listeners isn't necessarily bad, and there are no side-effects where I need to depend on the order or immediacy of garbage collection... but is there any other side-effects or potential problems with this approach?
And actually I was just thinking of one thing. If my listener is an annonymous class of a View object, does that mean that since somewhere a Model object has an collection with a reference to the listener, that my View object will never get garbage collected?
Similar Messages
-
Should I remove listeners?
I don't understand if it is my responsibility to remove every listeners associated to a variable, before I set it to null.
JTable aTable = new JTable( new SomeTableModel() );
aTable = new JTable( new SomeTableModel() );Even if this example isn't very correct, as I should have done setModel on the variable, should I remove the listeners from aTable before the last statement?
In other words, should one put special care before loose a reference to a complex component?
Actually, the setModel method in JTable.java removes the old listeners, suggesting to do the same in my example.
I don't remeber where I read that Sun put a new method into one of the last jdk releases, to obtain the List of listeners.
Thanks
EnricoWell, yes and no.
It is good practice to remove listeners but it is not nessecary.
The garbage collector in your case will after a unknown time notice that your program are not referencing the JTable at the moment and with that, also the table model and all other components are unreferenced from your program (read thread). Altough the JTable and table model might still reference your program, it should not care.
You might be careful thou if you for instance have an updater-thread running that slowly populates the model. If that thread is not removed, it will be referencing the table, and therefor neither thread, table or tablemodel will be garbage collected.
Regards,
Peter Norell -
Adding and removing listeners help please...
hi guys i have a pop up box that adds a listener depedent on a variable.
like such
if(upload_typ != 'O' && upload_typ != 'E')
{RPanel.DSUB.addEventListener(MouseEvent.CLICK, DatabaseSend)};
if(upload_typ == 'O')
{RPanel.DSUB.addEventListener(MouseEvent.CLICK, DataSendOntme)};
if (upload_typ == 'E')
{RPanel.DSUB.addEventListener(MouseEvent.CLICK, EncumSendVal)}
how do i remove the listeners? i continue to see examples of removing listeners but yet i dont see what the remove listener functions should do.
any help would be greatly appreciated.
MiguelIn your case, because you can't be sure what listener was added, you can remove them all, and if they have not been added, no harm:
RPanel.DSUB.removeEventListener(MouseEvent.CLICK, DatabaseSend);
RPanel.DSUB.removeEventListener(MouseEvent.CLICK, DataSendOntme);
RPanel.DSUB.removeEventListener(MouseEvent.CLICK, EncumSendVal);
Alternatively, you could register the ones that actually get added to an object (associative array) and remove only those when necessary.
If this post answers your question or helps, please mark it as such. Thanks!
http://www.chikaradev.com
Adobe Flex Development and Support Services -
Hi team,
Is it always best practice to remove every listener that you create in a project?
I thought I had this worked out but all of a sudden I am getting errors by trying to use the removed from stage listener.
So there are buttons on the stage and some movieclips that those buttons make visible and here is the code that I am trying to use, but it generates errors on leaving the frame. I think this is the same as what I have been using but somehow it is now not working for me.
Any help greatly appreciated
cheers
sub
taxb1.visible=false;
taxb2.visible=false;
taxb3.visible=false;
taxb4.visible=false;
taxbn1.addEventListener(MouseEvent.CLICK, taxb1go);
function taxb1go(e:MouseEvent){
taxb1.visible=true;
taxbn2.addEventListener(MouseEvent.CLICK, taxb2go);
function taxb2go(e:MouseEvent){
taxb2.visible=true;
taxbn3.addEventListener(MouseEvent.CLICK, taxb3go);
function taxb3go(e:MouseEvent){
taxb3.visible=true;
taxbn4.addEventListener(MouseEvent.CLICK, taxb4go);
function taxb4go(e:MouseEvent){
taxb4.visible=true;
taxbn4.addEventListener(Event.REMOVED_FROM_STAGE, taxremoved);
function taxremoved(e:Event){
taxbn1.removeEventListener(MouseEvent.CLICK, taxb1go);
taxbn2.removeEventListener(MouseEvent.CLICK, taxb2go);
taxbn3.removeEventListener(MouseEvent.CLICK, taxb3go);
taxbn4.removeEventListener(MouseEvent.CLICK, taxb4go);
taxbn4.removeEventListener(Event.REMOVED_FROM_STAGE, taxremoved);I don't know what your timeline looks like but I'm assuming you're using it heavily for this.
Gawd you're going to make me go to photoshop. Lets make this real easy and get a picture in here........
Here's an example of not being able to assign a new instance name over 2 frames:
In the above picture the object extends 2 frames. If you clicked on that second frame and changed the instance name, it would change it for frame 1 as well.
Here's 2 keyframes, and an example of where you could set 2 separate instance names:
In the above picture you are making 2 separate instances so therefore you can give each one a different instance name.
That out of the way......
Using the second image example because this is what I assume you are doing, when you go from frame 1 to 2, all your listeners assigned on frame 1 are gone. They will be garbage collected. You do not need to remove them yourself. However if you are programming for a mobile device then it's a good idea to remove them manually anyway to free up ram instantly.
Flash does a lot of things automagically for you. Removing your listeners when you change frames in the second picture is one of them. Setting a weak reference further reinforces that flash is making the right decision to clean up the listeners automatically in garbage collection for you.
Now..
If you REALLY want to remove them yourself, then remove them in the buttons MouseEvent.CLICK method rather than REMOVED_FROM_STAGE. It makes sense and it will always work.
e.g.
btn1.addEventListener(MouseEvent.CLICK, btnHandler, false, 0, true);
function btnHandler(e:MouseEvent):void
btn1.removeEventListener(MouseEvent.CLICK, btnHandler); // don't put the extra false, 0, true here or it will error
gotoAndStop(2);
You get the general idea.. remove 1 - 99999 listeners or whatever you want to do in the CLICK handler, then do what you want the button to do, like move to another frame. You don't need to worry about removing things you have on the timeline from the display list via code. If you use the timeline, the timeline will do that for you. -
Removing listeners when stage closed
Hi,
In my View Controller I am adding a couple of listeners to two TextFields as part of the 'initialize' method call. When exiting the View Controller where would the correct place be to remove those listeners?
Cheers
AndyDo you really need to? If you don't retain references to the stage, its scene, and the scene graph beyond where you need them, those listeners should go out of scope anyway.
If you need to structure things otherwise, doing this is possible but a little convoluted. Obviously, in your initialize() method, the text fields have not yet been added to a stage, or likely to a scene, so it's hard to register a listener with the stage. The trick is to listen to the window property of the scene property of the text fields (or any node in the same scene graph), and register a listener with the window when it is set. The following code does this, and also cleans up if the text field is removed from the scene (or the scene from the stage).
// textField in this line can be replaced by anything in the same scene (e.g. the root node of the scene)
final ObjectBinding<Window> windowBinding = Bindings.select(textField.sceneProperty(), "window");
final EventHandler<WindowEvent> windowClosedHandler = new EventHandler<WindowEvent>() {
@Override
public void handle(WindowEvent event) {
System.out.println("Window closed");
textField.textProperty().removeListener(textListener);
// this listener no longer needed:
if (event.getSource() instanceof Window) {
((Window)event.getSource()).removeEventHandler(WindowEvent.WINDOW_HIDDEN, this);
windowBinding.addListener(new ChangeListener<Window>() {
@Override
public void changed(ObservableValue<? extends Window> observable,
Window oldWindow, Window newWindow) {
if (oldWindow != null) {
oldWindow.removeEventHandler(WindowEvent.WINDOW_HIDDEN, windowClosedHandler);
if (newWindow != null) {
newWindow.addEventHandler(WindowEvent.WINDOW_HIDDEN, windowClosedHandler); -
Removing Event Listeners - Are they needed all the time
My goal is to increase the performance of my project so I would like to know if it is always a good idea to remove event listeners. More specifically, lets say I have a movie with severals scenes and several frames within those scenes. Each one of the frames has an event listener:
Example:
Scene 1
Frame 1 (EventListener)
Frame 2 (EventListener)
Frame 3 (EventListener)
Frame 4 (EventListener)
Scene 2
Frame 1 (EventListener)
Frame 2 (EventListener)
Frame 3 (EventListener)
Frame 4 (EventListener)
Questions:
Does Flash continue to listen for an event in Scene 1/Frame 1 when the playhead has moved to Scene 1/ Frame 2?
Or does Flash just listen for the events when the playhead is in a particular frame only?
Should I remove the event listener once I leave a particular frame (should there be remove event listeners on each frame)?Just mentioning, the addEventListener comes with a parameter you can set to true or false called a weak reference. On desktop flash apps it can become time consuming to constantly remove listeners, especially when things drop off the display list frame to frame. You can mark them for automatic garbage collection by using the weak reference property.
e.g.
Credits_bnt.addEventListener(MouseEvent.CLICK, goCredits, false, 0, true); // set weak reference to true (e.g. remove when no references exist anymore automatically)
Eventually garbage collection will remove that reference automatically when there's nothing left on the display list or in memory to use it.
However, if this is targeted at mobile, you absolutely want to remove the reference as soon as possible when it's not needed for memory conservation. On a desktop it's not that big of a deal. -
Best practice for adding and removing eventListeners?
Hi,
What is the best practice in regards to CPU usage and performance for dealing with eventListeners when adding and removing movieclips to the stage?
1. Add the eventListeners when the mc is instantiated and leave them be until exiting the app
or
2. Add and remove the eventListeners as the mc is added or removed from the stage (via an addedToStage and removedFromStage listener method)
I would appreciate any thoughts you could share with me. Thanks!
JPThanks neh and Applauz78.
As I understand it, the main concern with removing listeners is to conserve memory. However, I've tested memory use and this is not really an issue for my app, so I'm more concerned if there will be any effect on CPU (app response) if I'm constantly adding and removing a list of listeners every time a user loads an mc to the stage, as compared to just leaving them active and "ready to go" when needed.
Is there any way to measure CPU use for an AIR app on iOS?
(It may help to know my app is small - I'm talking well under 100 active listeners total for all movieclips combined.) -
ADDED event in document class after removed from Stage
Hi All,
I am currently play with the document class (the class acts as main) constructor for a SWF file.
package {
import flash.display.*;
import flash.events.*;
public class TestSymbol extends MovieClip
public function TestSymbol()
this.addEventListener(Event.ADDED, function(event:Event) { trace(event.eventPhase, event.target, event.currentTarget, "added triggered"); });
trace("parent", this.parent);
this.stage.removeChild(this);
trace("stage", this.stage);
In frame script 1, i put
trace("1");
trace("parent", this.parent);
After i run TestSymbol.swf and i got
parent [object Stage]
stage null
2 [object TestSymbol] [object TestSymbol] added triggered
1
parent null
I wonder where is this ADDED event coming from? If the document class is added to some other objects, why its parent is null after the event?
Thanks in advance
SamBy wrapper do you mean they are the same object or the MainTimeLine is a separate object being added to DocumentClass, as it triggers the ADDED event? I know that framescript can be accessed as documentClass functions, so I thought they are the same object, maybe i was wrong.
I did a new test within some more listeners
package {
import flash.display.*;
import flash.events.*;
public class TestSymbol extends MovieClip
public function TestSymbol()
this.addEventListener(Event.ADDED_TO_STAGE, addedToStageListener);
this.addEventListener(Event.ADDED, addedListener)
this.addEventListener(Event.REMOVED_FROM_STAGE, removedFromStageListener);
this.addEventListener(Event.REMOVED, removedListener);
trace("parent", this.parent);
this.stage.removeChild(this);
trace("stage", this.stage);
private function addedListener(event:Event):void {
trace(event.eventPhase, event.target, event.currentTarget, "added triggered");
private function addedToStageListener(event:Event):void {
trace(event.eventPhase, event.target, event.currentTarget, "addedToStage triggered");
private function removedListener(event:Event):void {
trace(event.eventPhase, event.target, event.currentTarget, "removed triggered");
private function removedFromStageListener(event:Event):void {
trace(event.eventPhase, event.target, event.currentTarget, "removedFromStage triggered");
and this is the output
parent [object Stage]
2 [object TestSymbol] [object TestSymbol] removed triggered
2 [object TestSymbol] [object TestSymbol] removedFromStage triggered
stage null
2 [object TestSymbol] [object TestSymbol] added triggered
As the remove listeners are fired immediately, i don't think the queue is waiting until the end of the constructor. -
Can any one explain me about Listeners in Java
Hi,
Can any one explain the Listeners concept in Java??
Will that work like net send in Windows NT??
How can we achieve the net send type of messaging in an Intenet application??
Is there any possibility??
Please help me out...
Thanks in advance,
Chaitanya.The idea is that the "observable" object holds a list of listening classes which conform to a given interface. When an event occurs it walks the list calling a specific method in all the listeners with whatever parameters are suitable to speficy the event. Very often the listeneing objects are inner classes of some larger class which implement whatever effect the event is to have on the larger class.
Anyonymous inner classes are a convenient abbreviation here.
Usually the observable class has methods called add???Listener and
remove???Listener to add and remove listeners from it's list. There's also often a protected method called fire???Listeners (where ??? is the event type).
So for instance:
public interface DirtyListener {
public void dirtyChanged(boolean to);
class DataModule {
private Set dirtListeners = new HashSet(10);
public void addDirtyListener(DirtyListener d) {
dirtListeners.add(d);
public void remiverDirtyListeners(DirtyListener d) {
dirtListeners.remove(d);
public void fireDirtyListeners(boolean to) {
Iterater it;
for(it = dirtyListeners.iterator(); it.hasNext();)
((DirtyListener)it->next()).dirtyChanged(to);
class ObservingClass {
DateModule data = new DataModule();
data.addDirtyListener(new DirtyListener() {
public void dirtyChanged(boolean to) {
saveButton.setEnabled(to); -
How do remove FDM from on 11.1.2.3 Dev environment.
I have installed FDM on my 11.1.2.3 Dev environment. Then few days later installed FDMEE in the same server. I believe I may have done a big mistake here. My goal now is too remove FDM and finalize FDMEE configuration. Currently, when trying to deploy FDMEE application I get the Deploy to Application server failed message. I have been looking on log files to identify the root cause, but I am not sure which log file is the correct one to view when we are deploying an application via the config tool. I am on a distributed windows 2008 r2 app server environment. I would appreciate any help. Thank you.
The error you stated:
Unable to access application source information in Oracle\Middleware\EPMSystem11R1\products\FinancialDataQuality\AppServer\InstalleableApps\aif.ear'
means that it can't access those files on the Weblogic admin server machine, are you sure the fdmee web application was installed on both machines.
Cheers
John
http://john-goodwin.blogspot.com/ -
This is my problem:
I have to freeze listeners of a button until another event has occurred (for example a press of another button).
What is the best way to do this?
(Consider I have a lot of graphical objects in different windows, I'm trying to catch a way that permits me to develop future code without
modifying so much the structure of the program and I don't want to waste resources ( I wouldn't remove listeners))Hi,
you could disable buttons, or have booleans and if they are true you return from the actionPerformed() or whatever methods.
Phil -
Listeners not working on refreshing View
Hi all
I have an application( Virtual WareHouse Monitor) which reads data froma text file and accordingly it generates a 3D view of the warehoue.
Actually when i reopen other new text file on my application , although the 3D view is displayed properly but for this re-opend files listeners are not working.However they were working for the first file.
I have used this code to refresh scene before re-opening a file if other file is previously open.
// removes branchgroup which use to show previous data
sceneBG.removeChild(warehouseBG);
sceneBG.removeChild(stockBG);
// add new data and objects
sceneBG.addChild(setWarehouseObjects());
sceneBG.addChild(refreshWarehouseStock());
It results in displaying 3D view for new file but mouse and keyboard listeners do not work.However, Picking works perfectly.
Do i need to remove listeners also while refreshing the scene?I tried to remove listeners and register it with new instances but still it does not works.
-
Remove stage listener for multiple movieclips
I would like to completely remove personalized stage listeners, for each movieclip as soon as they are placed where they need to be, but the listeners remain every single time a new clip is dragged.
Thank you for any help!
function clickToDrag(targetClip:MovieClip):Function {
return function(e:MouseEvent):void {
startingPosition[targetClip.name] = new Point(targetClip.x, targetClip.y);
targetClip.startDrag(false, new Rectangle(0,0,800,600));
setChildIndex(targetClip,numChildren - 1);
trace('clickToDrag function invoked\ntargetClip: ' + targetClip.name + '\startingPosition: ' + startingPosition[targetClip.name] + '\n\n');
stage.addEventListener(MouseEvent.MOUSE_UP, releaseToDrop);
/* releaseToDrop
@function stopDrag for current clip, if dropped off stage, returns to recorded beginning location
@param targetClip:MovieClip
@param startPosition:int
@returns event:void
function releaseToDrop(targetClip:MovieClip):Function {
return function(e:MouseEvent):void {
targetClip.stopDrag();
trace('releaseToDrop function invoked\ntargetClip: ' + targetClip.name + '\n\n');
stage.removeEventListener(MouseEvent.MOUSE_UP, releaseToDrop);
stage.addEventListener(Event.MOUSE_LEAVE, mouseGone);
function mouseGone () {
TweenLite.to(targetClip, .2, { x: startingPosition[targetClip.name].x });
TweenLite.to(targetClip, .2, { y: startingPosition[targetClip.name].y });
//toggle comments to ease or not ease back to startingPosition
//targetClip.x = startingPosition[targetClip.name].x;
//targetClip.y = startingPosition[targetClip.name].y;
stage.removeEventListener(Event.MOUSE_LEAVE, mouseGone);
trace('releaseToDrop function invoked\ntargetClip dragged out of bounds: ' + targetClip.name + '\n\n');
/* checkTarget
@function checks if current clip is dragged to drag1target(dock), updates boat weight and waterline, remove listeners
@param targetClip:MovieClip
@param lbsAmount:int
@param targetLocation:MovieClip
@returns event:void
function checkTarget(targetClip:MovieClip,lbsAmount:int,targetLocation:MovieClip):Function {
return function(e:MouseEvent):void {
if (targetClip.hitTestObject(drag1target)) {
targetClip.x = targetClip.x;
targetClip.y = targetClip.y;
drop.play();
TweenLite.to(targetClip, .5, { alpha: 0, onComplete:fadein });
function fadein() { TweenLite.to(targetLocation, .5, { alpha: 1 }); }
noMC.waterlineMC.y = noMC.waterlineMC.y - 3;
lbs -= lbsAmount;
lbsTxt.htmlText = lbs + "<font size='16'>lbs</font>";
targetClip.buttonMode = false;
targetClip.mouseEnabled = false;
targetClip.removeEventListener(MouseEvent.MOUSE_UP, checkTarget);
targetClip.removeEventListener(MouseEvent.MOUSE_DOWN, clickToDrag);
/* TODO: Issue with stage listener for every clip, opportunity to handle programmatically? */
/* check to see if eventListenter is still present */
if(targetClip.hasEventListener(MouseEvent.MOUSE_DOWN)) {
trace(targetClip.name + ' still has MOUSE_DOWN event listener');
if(targetClip.hasEventListener(MouseEvent.MOUSE_UP)) {
trace(targetClip.name + ' still has MOUSE_UP event listener');
} else if (borderMC.hitTestPoint(targetClip.x, targetClip.y, true)){
/*targetClip.y = startingPosition[targetClip.name].y;
targetClip.x = startingPosition[targetClip.name].x; */
TweenLite.to(targetClip, .2, { x: startingPosition[targetClip.name].x });
TweenLite.to(targetClip, .2, { y: startingPosition[targetClip.name].y });
} else {
/*targetClip.y = startingPosition[targetClip.name].y;
targetClip.x = startingPosition[targetClip.name].x; */
TweenLite.to(targetClip, .2, { x: startingPosition[targetClip.name].x });
TweenLite.to(targetClip, .2, { y: startingPosition[targetClip.name].y });i will try to show you a way that might help you to understand how the event-model in as3 is meant to work.
look at this code:
//with a MovieClip "DragClip" in the Library exoported for ActionScript
import flash.display.MovieClip;
import flash.events.MouseEvent;
for (var i:int = 0; i<10;i++){
var mc:DragClip = new DragClip();
addChild(mc);
mc.mouseChildren = false;
mc.addEventListener(MouseEvent.MOUSE_DOWN, dragStart);
mc.addEventListener(MouseEvent.MOUSE_UP, dragStop);
addChild(mc);
function dragStart(e:MouseEvent):void {
e.currentTarget.startDrag();
trace("dragging started");
function dragStop(e:MouseEvent):void {
e.currentTarget.stopDrag();
trace("dragging stopped");
e.currentTarget.removeEventListener(MouseEvent.MOUSE_DOWN, dragStart);
e.currentTarget.removeEventListener(MouseEvent.MOUSE_UP, dragStop);
//it places hundred Movieclips on the stage
//makes them draggable
//but after they are dragged once
//they stay in place -
Best Way to "Unload" or remove assets in AS3
I read G. Skinner's article on removing resources in AS3 and
garbage collection (
click
for relevant section of article) and I was a bit astounded.
I understand that one must be careful to manage memory --
remove listeners, add weak references, etc -- and clean up when you
go. I.e. I have a basic understanding of how to make assets, once
off the display list, eligible for garbage collection. But let's
say you load a SWF and it's running -- and particularly if this is
not your own SWF, e.g. in a gallery setting -- is there a way to
get rid of it? What if you load in a SWF, and it uses a lot
of CPU -- and you want it
gone when it's gone? Is there any way to really get rid of
things in AS3, or do you just make them eligible for GC and hope
for the best? This seems a very bad thing -- particularly, if, say,
you're loading in content over which you don't have control (as in
that proverbial gallery).no.
no.
yes.
and yes.
so, just say no to loading assets over which you have no
control. -
May be dumb - but I create a lot of objects in an application
written in 3.0. When they are done doing what they do, I would love
to be able to call a utility routine that shimply looped through
the listeners that are registered for all objects and remove them
where is .target is the object I am done with. I don't know if this
is possible but it would significantly simplify my code and I
suspect the internals of listener registration, removal and cycling
does the .target check anyways......
Am I barking up the wrong tree, is this something someone had
done or is the mere thought of it stupid from the start......
bobKglad - no, just the listeners. I would like something like
for each(listener in the listener stack) {
if listener.subscribed_to_target = mytarget
remove listener
In my coding - any listeners set up in an object are dealt
with by that object when done - typical remove_listeners funtion
removing listeners set-up, typically on instantiation of the
object. Listners that subscribe to the object events from other
objects deal with removal separately.
It would clean things up tremendously to simply walk the
listener stack and where the target is the object that is no longer
needed, I could have some iteration to remove all listeners that
have that object as a target.....
Hope this makes sense....
ccoonen - I fear the use of "weak reference" but do so as is
suggested in some texts. If I could confirm that the listener was
removed and collected as of a certain point I would follow your
strategy, but I always hesitate to rely on something I can not
test.
Maybe you are looking for
-
February 2012,I bought an AppleTV in the US, to bring it to where I live, CHILE, where voltage is 220V. Is the device multivoltage or do I need a voltage converter? Thanks!
-
My iPhone 5 got wet and I dried it out for 3 days. Now when I charge it the apple logo keeps blinking. Phone is unresponsive, so I tried to restore it but got error code 21. Tried on another computer and got error code 2006. Any suggestions, or is it
-
To whom it may Concern: On August 15, 2011 I placed a bundle package order for Verizon High Speed Internet and Direct TV. Direct TV came to my home three days later (8/18/11) and successfully installed their service. Verizon High Speed Internet was n
-
PowerMac G5 Image across single, dual, and quad Processor Macs
Good Day, Our organization is preparing to roll out Tiger. To streamline this process we have decided to create images for each Mac family in use. I know I need to find the newest possible model to create the image but what is the rule for single, du
-
Wheel next to faces will not stop spinning
So iPhoto was merrily plugging along when, the other day, I noticed that the update wheel next to faces began to spin...and spin...and spin. I quit iPhoto and, much to my chagrin, the wheel returned. The wheel continues to persist, even after I have