`
javastder
  • 浏览: 12131 次
  • 性别: 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
分享到:
评论

相关推荐

    Go To Statement Considered Harmful

    Dijkstra 在《ACM通讯》上发表了一篇题为“Go To Statement Considered Harmful”的文章,这篇文章引起了程序设计界长达数十年的争论。Dijkstra 认为 goto 语句是一种导致程序结构混乱的根源,并提出了结构化编程的...

    四六级考试作文经典句式

    Last but not least, more and more people prefer to enjoy modern life." 在使用时,考生应确保对每个句型的语法结构有清晰的理解,避免因套用错误而影响表达。 2. 表示好处 - It has the following ...

    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 ...

    基于新能源汽车技术原理探讨其优缺点的分析.pdf

    New energy vehicle technology refers to a more energy-efficient, low-carbon, and environmentally friendly automotive technology compared to traditional fossil fuel vehicles. This technology focuses on...

    雅思写作重点词汇.doc

    有害 (Harmful): 如“A is harmful to B”,例如,“私家车对环境有害(Private cars are harmful to the environment)”。还可以使用“对...不利(unfavorable)”,“有害的(detrimental)”,“对...不好(bad ...

    内蒙古北方重工业集团有限公司第三中学2014-2015学年高一英语下学期第一次月考试题

    Mice fed with a diet containing 25% more sugar had a higher death rate. C. Overconsumption of sugar doesn't necessarily lead to obesity or high blood pressure immediately. D. The study lasted for ...

    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 ...

    保护环境的英语句子.doc

    We should plant more and more trees in order to live better and more healthy in the future." 节约用水和植树造林是每个人应尽的责任,以改善未来的生活质量。 20. "We don't need to do big things—we can ...

    高中英语 Unit 4 Astronomy the science of the stars课前预习 新人教版必修3

    1. What it was to become was uncertain until between 4.5 and 3.8 billion years ago when the dust settled into a solid globe. 这个物体将要变成什么,在大约45亿到38亿年前,当尘埃凝聚成一个坚实的球体之前...

    英语四六级考试

    Last but not least, more and more people prefer to enjoy modern life." 2. **表示好处**: - It has the following advantages. - It does us a lot of good. - It benefits us quite a lot. - It is ...

    英语作文万能句子总结版.doc

    27. "Do harm to / be harmful to / be detrimental to" - 描述负面影响,"Excessive screen time can do harm to children's physical and mental health." 28. "Realize one's dream / make one's dream come ...

    山东省龙口市诸由观镇诸由中学九年级英语上册《Unit 8 We’re trying to save the earth》练习(无

    23. **lead/guide to** - 导向;引导 24. **hear about** - 听说 25. **a bowl of shark fin soup** - 一碗鲨鱼翅汤 26. **not only...but also...** - 不但…而且… 27. **be harmful to** - 对…有害 28. **not......

    保护环境的英语句子.pdf

    18. "We should plant more and more trees in order to live better and more healthy in the future." 种树能改善环境,为我们的未来创造更好的居住条件。 19. "We don't need to do big things—we can start ...

    英语四级真题大家看看哦

     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 ...

    Unit6-Section+A+-+exercises.pdf

    例如,题目中的" Fruit juices can be harmful to children’s teeth."表明果汁可能对儿童的牙齿有害,因此,我们需要用“有害的”(harmful)来形容这种影响。又如"He is also thought to suffer from a heart ...

    九年级英语下册Module5LookafteryourselfUnit2Getoffthesofa作业设计新版外研版202002

    more and more beautiful - 变得越来越美丽,形容词比较级的连用。 29. A. who - 引导定语从句,指代人。 30. A. Because - 因为她丈夫,她成为了一位著名的电影明星。 这些内容涵盖了英语中的词汇学习、短语运用...

    五年级英语下册Unit1Cinderella第3课时同步练习含解析牛津译林版三起

    - 因为这些蘑菇对我们有害:Because these mushrooms are harmful to us. 5. 阅读理解: - 故事内容讲述罗斯一家喜欢周日野餐,这周日他们计划去红公园。杰克和迈克,他们的儿子,早起准备。他们都穿上了牛仔裤和...

    2015届高考英语二轮专题检测精品练习 书面表达(3)

    Manufacturers, driven by the desire for higher profits, often neglect essential safety measures, leading to the circulation of substandard and potentially harmful food in the market. This poses ...

Global site tag (gtag.js) - Google Analytics