Главная » Просмотр файлов » Programming Java 2 Micro Edition for Symbian OS 2004

Programming Java 2 Micro Edition for Symbian OS 2004 (779882), страница 70

Файл №779882 Programming Java 2 Micro Edition for Symbian OS 2004 (Symbian Books) 70 страницаProgramming Java 2 Micro Edition for Symbian OS 2004 (779882) страница 702018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 70)

It is therefore worthseeing if we can do more in a given operation.JAR files are used to transfer multiple objects in one HTTP request.Using buffered streams means that we transfer multiple items of data atone time, rather than item by item or byte by byte. It is rare that unbufferedIO is required; buffered IO should always be the default.7.17Memory Management7.17.1 The Garbage CollectorIt is rare that a Java application will run out of memory on a desktopcomputer; however, this is not the case for mobile phones and otherconstrained devices. We should regard memory exceptions as the ruleand handle them gracefully.The KVM garbage collector does not return memory to the system.Freed memory will only be available to your application: it will notMEMORY MANAGEMENT389be available to other Java or native applications.

If you know you arerunning on the KVM, do not grab memory just in case you need it; youwill deprive other programs of this scarce resource. Even if you are onthe CLDC HI VM, it is more socially acceptable to request memory onlywhen you need it. Of course, once your application quits and the KVMexits, the memory it used will become available to other applications.Also remember that Vectors and recursive routines have unconstrainedmemory requirements.7.17.2 Memory LeaksJava has a different notion of a memory leak to C++.

In C++, a memoryleak occurs when a reference to an allocated object is lost beforedelete() is called on the object. If an object is no longer referencedin Java it will be garbage collected, so C++ style memory leaks cannotoccur.However, a similar effect is created by a Java object that is no longerused but is still referenced by another Java object. Care should therefore betaken to de-reference such objects.

It is particularly easy to leave objectshanging around in containers. CLDC 1.1 introduces weak references forjust this sort of situation.7.17.3 Defensive Coding to Handle Out-Of-Memory ErrorsHow can we protect users of our applications from out-of-memory errors?The previous section has highlighted the problem in picking up heapallocation failures. Fortunately, under Java, out-of-memory errors areunlikely to be caused by short-lived objects: the garbage collector shouldkick in before this happens. Here are some pointers:• once your application has started, check how much free memory isavailable (you can use freeMemory() from java.lang.Runtime)If there is insufficient memory (and only you can judge what thatmeans), give the user the opportunity to take appropriate actionsuch as closing down an application.

However, freeMemory() andtotalMemory() should be treated with caution because as memoryruns out, more memory will be provided to the MIDlet, up to the limitset at runtime or available in the phone.• create large objects or arrays in try – catch blocks and catch anyOutOfMemoryError exception that might be thrown; in the catchclause, do your best either to shut down gracefully or to take someaction that will allow the user to carry on• never call Runtime.gc(): there is no guaranteed behavior for thismethod; also, the garbage collector knows more about the memorysituation than you do, so leave it to get on with its job!3907.18WRITING OPTIMIZED CODEJIT and DAC CompilersMost applications benefit from improved compiler technology.

Thisshould not be seen as a panacea, though, because Java applicationsspend a lot of their time executing native code. Many JSRs, for examplethe Mobile Media API (JSR 135) and Bluetooth APIs (JSR 82), are comparatively thin veneers over native technology.7.18.1Just In Time CompilersJITs have proved popular in enterprise and desktop applications wherea lot of memory is available. A JIT is a code generator that convertsJava bytecode into native machine code, which generally executes morequickly than interpreted bytecodes.

Typically most of the applicationcode is converted, hence the large memory requirement.When a method is first called, the JIT compiler compiles the methodblock into native code which is then stored. If code is only called onceyou will not see a significant performance gain; most of the gain isachieved the second time the JIT calls a method. The JIT compiler alsoignores class constructors, so it makes sense to keep constructor code toa minimum.7.18.2 Java HotSpot Technology and Dynamic Adaptive CompilationJava HotSpot virtual machine technology uses adaptive optimization andbetter garbage collection to improve performance.

Sun has created twoHotSpot VMs, CDC HI and CLDC HI, which implement the CDC andCLDC specifications respectively. HI stands for HotSpot Implementation.A HotSpot VM compiles and inlines methods that it has determinedare used the most by the application. This means that on the first pass Javabytecodes are interpreted as if there were no enhanced compiler present.If the code is determined to be a hotspot, the compiler will compile thebytecodes into native code. The compiled code is patched in so that itshadows the original bytecode when the method is run and patched outagain when the retirement scheme decides it is not worth keeping aroundin compiled form.CLDC HI also supports ”on-stack replacement”, which means that amethod currently running in interpreted mode can be hot-swapped forthe compiled version without having to wait for the method to return andbe re-invoked.An advantage of selective compilation over a JIT compiler is that thebytecode compiler can spend more time generating highly-optimizedcode for the areas that would benefit most from optimization.

By thesame token, it can avoid compiling code when the performance gain,memory requirement, or startup time do not justify doing so.OBFUSCATORS391The HotSpot garbage collector introduces several improvements overKVM-type garbage collectors:• the garbage collector is a ‘‘fully-accurate’’ collector: it knows exactlywhat is an object reference and what is just data• the garbage collector uses direct references to objects on the heaprather than object handles: this reduces memory fragmentation, resulting in a more compact memory footprint• the garbage collector uses generational copyingJava creates a large number of objects on the heap, and often theseobjects are short-lived. By placing newly-created objects in a memory”nursery”, waiting for the nursery to fill, and then copying only theremaining live objects to a new area, the VM can free in one go theblock of memory that the nursery used.

This means that the VM doesnot have to search for a hole in the heap for each new object, andthat smaller sections of memory are being manipulated.For older objects, the garbage collector makes a sweep through theheap and compacts holes from dead objects directly, removing theneed for a free list as used in earlier garbage collection algorithms.• the perception of garbage collection pauses is removed by staggeringthe compacting of large free object spaces into smaller groups andcompacting them incrementally.The Java HotSpot VM improves existing synchronized code. Synchronizedmethods and code blocks have always had a performance overheadwhen run in a Java VM. HotSpot implements the monitor entry andexit synchronization points itself, rather than depending on the local OSto provide this synchronization.

This results in a large improvement inspeed, especially for heavily-synchronized GUI applications.7.19 ObfuscatorsClass files carry a lot of information from the original source file, neededfor dynamic linking. This makes it fairly straightforward to take a classfile and reverse-compile it into a source file that bears an uncannyresemblance to the original, including names of classes, methods andvariables.Obfuscators are intended to make this reverse compilation processless useful. However, they also use a variety of techniques to reducecode size and, to a lesser extent, enhance performance, for example byremoving unused data and symbolic names from compiled Java classesand by replacing long identifiers with shorter ones.392WRITING OPTIMIZED CODESun ONE Studio Mobile Edition gives access to two obfuscators:RetroGuard and Proguard.

RetroGuard is included with the IDE. Proguardhas to be downloaded separately (see proguard.sourceforge.net), but theIDE provides clear instructions. As an example, the size of the ‘‘straight’’LifeTime JAR file is 13 609 bytes; JARing with RetroGuard reduced thisto 10 235 bytes and with Proguard to 9618 bytes. The benefits are fasterdownload time and less space needed on the phone.7.20SummaryWe have looked at a various ideas for improving the performance ofour code, and in Section 7.4 we listed a number of guiding principles.Perhaps the most important are these:• always optimize, but especially on constrained devices• identify the performance and memory hotspots and fix them• get the design right.It is possible on a desktop machine to get away with a poorly-designedJava application.

However, this is not true on mobile phones. Thecorollary is also true: a well-designed Java application on a mobile phonecan outperform a badly-designed application on a desktop machine.By thinking carefully about design and optimization we can createsurprisingly complex Java applications that will perform just as effectivelyas an equivalent C++ application.Finally, an anonymous quote I came across: ‘‘I’ve not seen a wellarchitected application that was both fast and compact. But then I’venever seen a fast and compact application that was also maintainable.’’This is perhaps an extreme view, but it is certain that if you have anyintention of maintaining your application into the future, or reusing ideasand components for other applications, you should ensure that you havearchitected it well!Section 3The Evolution of the Wireless JavaMarket8The Market, the Opportunitiesand Symbian’s Plans8.1 IntroductionMuch of this book has dealt with deeply technical aspects of Javadevelopment on Symbian OS phones, with the broad goal of helping youto write better and more useful MIDlets for Symbian OS.

This chapterlooks at the market for Java technology on mobile phones in general andSymbian OS in particular; in other words, at the opportunities you haveas a Symbian OS Java developer. It provides estimates for the value of themarket, discusses the needs of the various market segments and looks atmarket opportunities, especially for advanced consumer services.We will discuss Symbian’s approach to Java and how the companyis responding to market requirements.

This includes a detailed look atSymbian’s plans for implementing Java technology over the next coupleof years.We end the chapter with some thoughts on what might be the significant technology trends and related market trends.8.2 The Wireless Java Market8.2.1 Market SizeThis section looks at what is happening, and what is likely to happen,in the wireless Java market.

Характеристики

Тип файла
PDF-файл
Размер
5,73 Mb
Материал
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
Как Вы думаете, сколько людей до Вас делали точно такое же задание? 99% студентов выполняют точно такие же задания, как и их предшественники год назад. Найдите нужный учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6294
Авторов
на СтудИзбе
314
Средний доход
с одного платного файла
Обучение Подробнее