`
javastder
  • 浏览: 11788 次
  • 性别: Icon_minigender_1
  • 来自: 北京
最近访客 更多访客>>
文章分类
社区版块
存档分类
最新评论

System.gc Even More Harmful A Guide To WeakReferences

阅读更多

I wrote a couple of times about how problematic System.gc is for mobile developers, I'd like to drive that point further today.
LWUIT started making heavy use of WeakReference's in the past few months, which is something I've been using for a while now on SE but was reluctant to go for in ME. Not anymore, they solve allot of problems in the constrained device area and make our lives much easier.

They do have one drawback System.gc() breaks them, but I digress. First lets go over what a WeakReference is since I find that even experienced Java programmers are unfamiliar with this remarkably useful tool.

WeakReferences are a part of JavaSE since Java 2 (JDK 1.2) and a part of CLDC 1.1 and higher. A weak reference is a remarkably simple object it just includes a get() method returning a different object... That in itself is not so useful, however it is useful since the WeakReference has special treatment by the garbage collector in Java.

The Java garbage collector works by traversing the heap and "marking" every object it encounters in the object graph (everything to which we have a reference/pointer). Everything that is "unmarked" is potential garbage.
When walking across the heap if the garbage collector encounters a weak reference it will not traverse further, so unless you have an actual pointer to the content in the other side of the reference it can be collected if necessary.

This is very useful for caching which is probably the best performance optimization you can perform, by keeping a weak reference to data you can reuse an existing object/resource but allow it to be removed when you run out of space.

E.g. In LWUIT the bitmap fonts used to always cache two colors to support the common case of selected/unselected color switching.
This is good, but might be wasteful for cases where you have a unique font for the title which will never change its color... By leveraging weak references we can cache more than 2 colors easily (for special cases) while releasing redundant data for fonts that only use one color. All of this is handled seamlessly by the VM.

How does this work?

To use a weak reference just use:
myRef = new WeakReference(myObject);

Later on when you need to use your object you will need to extract it from the reference:
MyObjectType myInstance = (MyObjectType)myRef.get();
if(myInstance == null) {
// need to recreate and cache the object
myInstance = create();
myRef = new WeakReference(myInstance);
}
// use myInstance


Notice that when myInstance is assigned you have a "real" pointer to the object, as long as that exists it doesn't matter if you have or don't have a weak reference the object won't be collected.

This brings me back to System.gc(), it will eliminate all cached objects whether needed or not hence harming application performance further. We eliminated all of LWUIT's internal calls to System.gc (that are not related to exceptions) to avoid this sort of problem and we recommend everyone does the same to maximize font and image scaling performance.

One last tip which is a common question we get allot. Resource files often contain multiple images, caching them can become very expensive. However, opening a resource file must read the whole file since CLDC has no ability to seek an offset within files...
Assuming you want only some images from a resource file you can keep the resource file in a weak reference and keep a Hashtable of image names to weak refrences for images. This allows you to lazily load a resource file and featch only the necessary images but still allows the GC to remove unnecessary images.


Read more: http://lwuit.blogspot.com/2009/02/systemgc-even-more-harmful-guide-to.html
分享到:
评论

相关推荐

    beginning_portable_shell_scripting_from_novice_to_professional.pdf

    introduction to Shell Scripting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1 About This Book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ....

    CX-400 SERIES Ver.2选型.pdf

    harmful effects of coolants. These sensors can be used with confidence even around metal processing machinery that disperses oil mists. The protection mechanism also conforms to IP67 (IEC). CX-41□/42...

    Go To Statement Considered Harmful

    1968年,荷兰计算机科学家E•W•Dijkstra在《ACM通讯》上发表了... <br>这份PDF就是那篇文章的英文版 <br>http://www.u.arizona.edu/~rubinson/copyright_violations/Go_To_Considered_Harmful.html<br><br><br>

    Atmospheric Monitoring with Arduino

    Makers around the globe are building low-cost devices to monitor the environment, and ... You'll also discover how to use the scientific method to help you learn even more from your atmospheric tests.

    Scripts.zip_9L5F_9M5_GFDM_GFDM Channel_tv white space

    maintain low out-of-band radiation to avoid harmful interference to incumbent services like TV signals and wireless microphones. For this reason, a flexible digital radio with multicarrier modulation ...

    The Healthy Programmer

    3. A Farewell to Chairs? . . . . . . . . . . 29 Sitting Is Considered Harmful 30 3.1 3.2 Standing Up for the Truth 34 3.3 Enhancing Your Workstation 38 3.4 Retrospective 43 4. Agile Dieting . . . . . ...

    The Art of SQL

    It is quite often that what appears to be the common-sense and safe approach ends up being extremely harmful. Writing inefficient code and relying on experts for tuning the "bad SQL" is actually ...

    全国六级作文万能模板 这个word是03的!!~~

    These harmful side effects of autos burden our society with unacceptable costs to human health, the environment, and our economy.  So we must reverse this rising trend and promote the mass ...

    英语四级真题大家看看哦

     Some changes have taken place in people’s diet in the past five years.The major reasons for these changes are not far to seek.Nowadays,more and more people are switching from grain to meat for ...

    全国六级作文万能模板 不好意思,word是07的!!~~

    These harmful side effects of autos burden our society with unacceptable costs to human health, the environment, and our economy.  So we must reverse this rising trend and promote the mass ...

    英语四级范文,好好欣赏。

    Indeed, it is very unwise for college students to keep distance from physical exercise because physical exercise is not harmful but good to them.  College students can benefit a lot from physical ...

    四级英语复习重点

    They consider it harmful to do X. They firmly point out that 反对X 的第一个理由。 An example can give the details of this argument: 一个例子。 There is some truth in both arguments. But I think the...

    Vagaa哇嘎画时代--体验群体智慧的力量!

    This License does not permit you to install the Software on more than one computer at a time. You may make copies of the Software in machine-readable form for backup purposes only. The backup copy ...

    Regulatory Compliance and Safety Information for Catalyst 2960-S

    These limits are designed to provide reasonable protection against harmful interference when the equipment is operated in a commercial environment. This equipment generates, uses, and can radiate ...

    GM foods harmful or helpful.pdf

    GM foods harmful or helpful.pdf

    学位英语考试语法.pdf

    1、主语:是句子要说明的人或物,可以作主语的成分有名词...4) Smoking is harmful to the health.动名词作主语 5) To swim in that pool is a great pleasure.动词不定式作主语 6) What we shall do next is not yet de

    冰果英语智能作文系统.docx

    Apart from that, the gases that a car discharges are usually harmful to the environment. The carbon dioxide, for example, contributes to the global warming, which leads to environmental crisis of ...

    Reward Rate Maximization and Optimal

    death, which is harmful to the functions of the WSN, and has negative impact on the quality of service of the network. With temporal death being taken into account, this paper proposes a novel and ...

    FBMC and GFDM Interference Cancellation Schemes for FDR PHY Design

    A simple interference cancellation technique called serial inter-carrier interference cancellation scheme has been used to improve performance of the GFDM system. Channel equalization techniques have...

    Preliminary communication: Examination of the harmful effect to fetuses of fumonisin B1 in pregnant sows

    Preliminary communication: Examination of the harmful effect to fetuses of fumonisin B1 in pregnant sows Teratogenesis, Carcinogenesis, and Mutagenesis 20:293–299 (2000) TCM 277 :copyright: 2000 ...

Global site tag (gtag.js) - Google Analytics