I have a pretty big Flex & Papervision3D application that creates and destroys objects continually. It also loads and unloads SWF resource files too. While it's running the SWF slowly consumes memory til about 2GB when it croaks the player. Obviously I am pretty sure I let go of reference to instances I no longer want with expectation the GC will do its job. But I am having a heck of a time figuring out where the problem lies.
I've tried using the profiler and its options for capturing memory snapshots, etc - but my problem remains evasive. I think there are known problems using debug Flash player also? But I get no joy using the release version either.
How do you go about tracking down memory leak problems using FLEX/AS3 ? What are some strategies, tricks, or tools you have used to locate consumption
I usually implement a cleanup method in every class I make (since AS doesn't have destructors). The main problem I've noticed with the GC is with event listeners. Additional to what dirkgently said, also try to avoid anonymous listener functions (as you can't explicitly remove them). Here are a few links you may find useful:
Understanding Memory Leaks in ActionScript
Garbage Collection with Flex and Adobe Air
I stumbled across something explaining how to use Flex Profiler in Flex Builder and it was a HUGE help to me in debugging memory leaks. I would definitely suggest trying it out. It's very easy to use. Some things I found when profiling my applications:
Avoid using collections (at least LARGE collections) as properties of Value Objects. I had several types of Value Object Classes in my Cairngorm application, and each had a "children" property which was an ArrayCollection, and was used for filtering. When profiling, I found that these were one of my biggest memory eaters, so I changed my application to instead store the "parentId" as an int and use this for filtering. The memory used was cut drastically. Something like this:
Old way:
public class Owner1
{
public var id:int;
public var label:String;
public var children:ArrayCollection; // Stores any number of Owner2 Objects
}
public class Owner2
{
public var id:int;
public var label:String;
public var children:ArrayCollection; // Stores any number of Owner3 Objects
}
public class Owner3
{
public var id:int;
public var label:String;
}
New Way:
public class Owner1
{
public var id:int;
public var label:String;
}
public class Owner2
{
public var id:int;
public var label:String;
public var parentId:int; // Refers to id of Owner1 Object
}
public class Owner3
{
public var id:int;
public var label:String;
public var parentId:int; // Refers to id of Owner2 Object
}
I would also suggest removing event listeners when they are no longer needed.
because of issues like this I've developed a open source library that helps monitor all the events your running at any given time. its really easy to implement and i've re-factored projects in 10-15 minutes converting them to use the EventController i've developed.
basically for your scenario i would run through all the events and replace them from:
obj.addEventListener(...);
to :
EC.add(obj,...);
the rest is the same what that would do is register the event and make it crazy easy to see all your events at any point you want using the EC.log();
all the details and documentation are on my site i would love to know if this helps you and if you start working with it. if you have any feedback good or bad please feel free to post it up and i would look into it!
the site is:
http://fla.as/ec/
If your memory leak grows exponentially, it probably means GC is failing to do its job. Take a look at your code and see wherever you can decrease your objects' reference counts (by setting them to null). Make event-handlers weak. And re-profile.
Related
I'm really having problems resolving this.
The 'HandleNewTag' method is in the Droid MainActivity class. It's a non static but complains about the 'MainPage.HandleNFC' method it's calling, so I changed that to static and it didn't error.
The 'MainPage.HandleNFC' method also calls a method which was non static. I changed it to a static void to stop the error. Then inside that method, where it sets some properties of a XAML control, it complains that the control is not static which I am unable to change.
I've searched high and low on the internet to resolve this and although I can find similar errors, none of them refer to a non static control issue.
MainActivity.cs
public void HandleNewTag(object sender, NfcFormsTag e)
{
//MainPage mp = new MainPage();
byte[] bytes = e.Id;
Console.WriteLine(BitConverter.ToString(bytes));
if (BitConverter.IsLittleEndian)
Array.Reverse(bytes);
Console.WriteLine(BitConverter.ToString(bytes));
// Call method to send byte stream across machine boundaries.
// Receive byte stream from beyond machine boundaries.
Console.WriteLine(BitConverter.ToString(bytes));
if (BitConverter.IsLittleEndian)
Array.Reverse(bytes);
Console.WriteLine(BitConverter.ToString(bytes));
int result = BitConverter.ToInt32(bytes, 0);
MainPage.HandleNFC(result.ToString());
}
MainPage.xaml
public static void HandleNFC(string convertedtag)
{
addToReadout(convertedtag);
}
public static void addToReadout(string text)
{
Label label1 = new Label { Text = "Successfully clocked out # " + text, TextColor = Color.Black };
StackLayout sl = new StackLayout();
readOut.Children.Add(label1);
readOut.BackgroundColor = Color.Black;
readOut.Children.Count();
}
Something is wrong here. Why would you be calling your Forms MainPage (living in PCL or Shared Project) from the Xamarin.Android MainActivity? The dependency flow there is backwards. I'm also assuming "MainPage.xaml" is "MainPage.xaml.cs" as you are showing C# code and not XAML.
Either way, it looks like you want to add tags to a control on your MainPage. The HandleNewTag event handler living in MainActivity.cs probably shouldn't work like this because your solution will get complicated when you have to think about the other platforms. Typically you want your calls to triage from your PCL down to the platform specific projects, like what Xamarin.Forms.DependencyService does (basic container/IoC patterns).
I understand that on Android the NFC capabilities would require the Application or Activity Context to perform actions and the NFC readings you receive are coming in through your MainActivity. One way to handle this would be the MessagingCenter built into Xamarin.Forms. It was designed just for this purpose because then you can also send messages through the MessagingCenter from your iOS or UWP projects and everything will work fine. You would have one MessagingCenter subscription that lives in your MainPage.xaml.cs, I typically will use the constructor for that stuff.
Another option would be to create an "AppViewModel" that lives at your top level of your application. I typically make this a static variable in my App class so I can reference it from anywhere by calling App.ViewModel.(whatever). Your challenge will be taking that data and updating your UI. I would do this by just binding controls directly to the sources in that static instance and creating a "Refresh" mechanism that utilizes OnPropertyChanged to update the bindings. This is of course a more complex solution and is really built/designed around what you are trying to do exactly.
I hope this helps!
Disclosure: I work for Xamarin/Microsoft
I suspect a problem with an old version of the ObjectBuilder which once was part of the WCSF Extension project and meanwhile moved into Unity. I am not sure whether I am on the right way or not so I hope someone out there has more competent thread-safety skills to explain whether this could be an issue or not.
I use this (outdated) ObjectBuilder implementation in an ASP.Net WCSF web app and rarely I can see in the logs that the ObjectBuilder is complaining that a particular property of a class cannot be injected for some reason, the problem is always that this property should never been injected at all. Property and class are changing constantly. I traced the code down to a method where a dictionary is used to hold the information whether a property is handled by the ObjectBuilder or not.
My question basically comes down to: Is there a thread-safety issue in the following code which could cause the ObjectBuilder to get inconsistent data from its dictionary?
The class which holds this code (ReflectionStrategy.cs) is created as Singleton, so all requests to my web application use this class to create its view/page objects. Its dictionary is a private field, only used in this method and declared like that:
private Dictionary<int, bool> _memberRequiresProcessingCache = new Dictionary<int, bool>();
private bool InnerMemberRequiresProcessing(IReflectionMemberInfo<TMemberInfo> member)
{
bool requires;
lock (_readLockerMrp)
{
if (!_memberRequiresProcessingCache.TryGetValue(member.MemberInfo.GetHashCode(), out requires))
{
lock (_writeLockerMrp)
{
if (!_memberRequiresProcessingCache.TryGetValue(member.MemberInfo.GetHashCode(), out requires))
{
requires = MemberRequiresProcessing(member);
_memberRequiresProcessingCache.Add(member.MemberInfo.GetHashCode(), requires);
}
}
}
}
return requires;
}
This code above is not the latest version you can find on Codeplex but I still want to know whether it might be the cause of my ObjectBuilder exceptions. While we speak I work on an update to get this old code replaced by the latest version. This is the latest implementation, unfortunately I cannot find any information why it has been changed. Might be for a bug, might be for performance...
private bool InnerMemberRequiresProcessing(IReflectionMemberInfo<TMemberInfo> member)
{
bool requires;
if (!_memberRequiresProcessingCache.TryGetValue(member.MemberInfo, out requires))
{
lock (_writeLockerMrp)
{
if (!_memberRequiresProcessingCache.TryGetValue(member.MemberInfo, out requires))
{
Dictionary<TMemberInfo, bool> tempMemberRequiresProcessingCache =
new Dictionary<TMemberInfo, bool>(_memberRequiresProcessingCache);
requires = MemberRequiresProcessing(member);
tempMemberRequiresProcessingCache.Add(member.MemberInfo, requires);
_memberRequiresProcessingCache = tempMemberRequiresProcessingCache;
}
}
}
return requires;
}
The use of the hash code looks problematic if you run a very large number of classes / members, as can happen with the singleton approach you mentioned.
The double lock was totally odd in the old one (Only one thread goes into the whole section in all cases). Note that locking as the first thing certainly hurts performance. It is a trade of, notice that instead they create a copy to avoid modifying the list as it is being read.
I was wondering how TransactionScope class works to keep the transaction between different method calls (without the need to pass it as a parameter) and I came to this doubt. I've got two considerations about this question:
1
Looking into TransactionScope's implementation through Telerik JustDecompile, I've found that the current transaction is stored in a ThreadStatic member of the System.Transactions.ContextData class (code below).
internal class ContextData
{
internal TransactionScope CurrentScope;
internal Transaction CurrentTransaction;
internal DefaultComContextState DefaultComContextState;
[ThreadStatic]
private static ContextData staticData;
internal WeakReference WeakDefaultComContext;
internal static ContextData CurrentData
{
get
{
ContextData contextDatum = ContextData.staticData;
if (contextDatum == null)
{
contextDatum = new ContextData();
ContextData.staticData = contextDatum;
}
return contextDatum;
}
}
public ContextData()
{
}
}
The CurrentData property is called by TransactionScope's PushScope() method, and the last one is used by most of the TransactionScope constructors.
private void PushScope()
{
if (!this.interopModeSpecified)
{
this.interopOption = Transaction.InteropMode(this.savedCurrentScope);
}
this.SetCurrent(this.expectedCurrent);
this.threadContextData.CurrentScope = this;
}
public TransactionScope(TransactionScopeOption scopeOption)
{
// ...
this.PushScope();
// ...
}
Ok, I guess I've found how they do that.
2
I've read about how bad is to use ThreadStatic members to store objects within ASP.NET (http://www.hanselman.com/blog/ATaleOfTwoTechniquesTheThreadStaticAttributeAndSystemWebHttpContextCurrentItems.aspx) due the ASP.NET thread switching that might occur, so this data can be lost among the worker threads.
So, it looks like TransactionScope should not work with ASP.NET, right? But as far I have used it on my web applications, I don't remember any problem that I've run into about transaction data being lost.
My question here is "what's the TransactionScope's trick to deal with ASP.NET's thread switching?".
Did I make a superficial analysis on how TransactionScope stores its transaction objects? Or TransactionScope class wasn't made to work with ASP.NET, and I can be considered a lucky guy that never had any pain about it?
Could anyone who knows the "very deep buried secrets" of .NET explain that for me?
Thanks
I believe ASP.NET thread switching happens only in specific situations (involving asych IO operations) and early in the request life cycle. Typically, once the control is passed to the actual http handler (for example, Page), thread does not get switched. I believe that in most of situation, transaction scope will get initialized only after that (after page_init/load) and should not be an issue.
Here are few links that might interest you:
http://piers7.blogspot.com/2005/11/threadstatic-callcontext-and_02.html
http://piers7.blogspot.com/2005/12/log4net-context-problems-with-aspnet.html
I am developing an application in GWT as my Bachelor's Thesis and I am fairly new to this. I have researched asynchronous callbacks on the internet. What I want to do is this: I want to handle the login of a user and display different data if they are an admin or a plain user.
My call looks like this:
serverCall.isAdmin(new AsyncCallback<Boolean>() {
public void onFailure(Throwable caught) {
//display error
}
public void onSuccess(Boolean admin) {
if (!admin){
//do something
}
else{
//do something else
}
}
});
Now, the code examples I have seen handle the data in the //do something// part directly. We discussed this with the person who is supervising me and I had the idea that I could fire an event upon success and when this event is fired load the page accordingly. Is this a good idea? Or should I stick with loading everything in the inner function? What confuses me about async callbacks is the fact that I can only use final variables inside the onSuccess function so I would rather not handle things in there - insight would be appreciated.
Thanks!
Since the inner-class/ anonymous function it is generated at runtime it needs a static memory reference to the variables it accesses. Putting final to a variable makes its memory address static, putting it to a safe memory region. The same happens if you reference a class field.
Its just standard java why you can only use Final variables inside an inner-class. Here is a great discussion discussing this topic.
When I use the AsyncCallback I do exactly what you suggested, I fire an event though GWT's EventBus. This allows several different parts of my application to respond when a user does log in.
I'm having some trouble with memory management in a flash app. Memory usage grows quite a bit, and I've tracked it down to the way I load assets.
I embed several raster images in a class Embedded, like this
[Embed(source="/home/gabriel/text_hard.jpg")]
public static var ASSET_text_hard_DOT_jpg : Class;
I then instance the assets this way
var pClass : Class = Embedded[sResource] as Class;
return new pClass() as Bitmap;
At this point, memory usage goes up, which is perfectly normal. However, nulling all the references to the object doesn't free the memory.
Based on this behavior, looks like the flash player is creating an instance of the class the first time I request it, but never ever releases it - not without references, calling System.gc(), doing the double LocalConnection trick, or calling dispose() on the BitmapData objects.
Of course, this is very undesirable - memory usage would grow until everything in the SWFs is instanced, regardless of whether I stopped using some asset long ago.
Is my analysis correct? Can anything be done to fix this?
Make sure you run your tests again in the non-debug player. Debug player doesn't always reclaim all the memory properly when releasing assets.
Also, because you're using an Embedded rather than loaded asset, the actual data might not ever be released. As it's part of your SWF, I'd say you could reasonably expect it to be in memory for the lifetime of your SWF.
Why do you want to use this ???
var pClass : Class = Embedded[sResource] as Class;
return new pClass() as Bitmap;
Sometimes dynamically resource assignment is buggy and fails to be freed up. I had similar problems before with flash player and flex, for ex. loading and unloading the same external swf... the memory was increasing constantly with the size of the loaded swf without going down even if I was calling the system.gc(); after unloading the swf.
So my suggestion is to skip this approach and use the first case you have described.
UPDATE 1
<?xml version="1.0" encoding="utf-8"?>
<s:Application
xmlns:fx = "http://ns.adobe.com/mxml/2009"
xmlns:s = "library://ns.adobe.com/flex/spark"
xmlns:mx = "library://ns.adobe.com/flex/mx"
creationComplete = "creationComplete()">
<fx:Script>
<![CDATA[
[Embed(source="/assets/logo1w.png")]
private static var asset1:Class;
[Embed(source="/assets/060110sinkhole.jpg")]
private static var asset2:Class;
private static var _dict:Dictionary = new Dictionary();
private static function initDictionary():void
{
_dict["/assets/logo1w.png"] = asset1;
_dict["/assets/060110sinkhole.jpg"] = asset2;
}
public static function getAssetClass(assetPath:String):Class
{
// if the asset is already in the dictionary then just return it
if(_dict[assetPath] != null)
{
return _dict[assetPath] as Class;
}
return null;
}
private function creationComplete():void
{
initDictionary();
var asset1:Class = getAssetClass("/assets/logo1w.png");
var asset2:Class = getAssetClass("/assets/060110sinkhole.jpg");
var asset3:Class = getAssetClass("/assets/logo1w.png");
var asset4:Class = getAssetClass("/assets/060110sinkhole.jpg");
var asset5:Class = getAssetClass("/assets/logo1w.png");
}
]]>
</fx:Script>
At this point, memory usage goes up,
which is perfectly normal. However,
nulling all the references to the
object doesn't free the memory.
That's also perfectly normal. It's rare for any system to guarantee that the moment you stop referencing an object in the code is the same moment that the memory for it is returned to the operating system. That's exactly why methods like System.gc() are there, to allow you to force a clean-up when you need one. Usually the application may implement some sort of pooling to keep around objects and memory for efficiency purposes (as memory allocation is typically slow). And even if the application does return the memory to the operating system, the OS might still consider it as assigned to the application for a while, in case the app needs to request some more shortly afterwards.
You only need to worry if that freed memory is not getting reused. For example, you should find that if you create an object, free it, and repeat this process, memory usage should not grow linearly with the number of objects you create, as the memory for previously freed objects gets reallocated into the new ones. If you can confirm that does not happen, edit your question to say so. :)
It turns out I was keeping references to the objects that didn't unload. Very tricky ones. The GC does work correctly in all the cases I described, which I suspected may have been different.
More precisely, loading a SWF, instancing lots of classes defined in it, adding them to the display list, manipulating them, and then removing all references and unloading the SWF leaves me with almost exactly the same memory I started with.