Enterprise grade performances tuning with critical memory constraints (part 2) @ Cédric Walter | Friday, Oct 19, 2007 | 5 minutes read | 937 Words | Update at Friday, Dec 29, 2023
Tags: java

Still not enough, we were forced to profile the java code and make some big changes. ( from part 1 )

Profiling

You either profile an application for speed and/or memory usage and/or memory leaks. Our application is fast enough at the moment. Our major concern is optimizing memory usage and thus avoiding disk memory swapping.

Some words about architecture


It is not possible to profile any applications without having a deep understanding of the architecture behind. The Product Catalog is an innovative product which is a meta model for storing insurances product in a database, a Product is read only and can derivate instance that we call Policies. Policies are users data holder, containing no text, just values, and sharing a similar structure as the Product. This let the product know everything about (cross) default values, (cross) validations, multiple texts, attributes order/length/type etc and thus separate definition (Products) from implementation (Policies). Products and Policies can be fully described with Bricks, Attributes in a tree manner.

Reduce the number of object created


Looking at the code, we have seen that too many Products (17 Products has 15000 objects either Attributes/Bricks/Texts/Value/ValueRange) were loaded in memory. While this is clearly giving a speed advantage on an application server, it is simply killing the offline platform with it 1GB RAM (remember memory really free is 500Mb) The problem is that Attributes and Brick are using/can use a lot of fields/meta data in the database which translate into simple java type (String for UUID, and meta data keys and values) in memory. We start looking at the profiler and the 100 MB used by the product cache. Reducing this amount of object was the first priority, a lot of them are meta data which are common and spread across the Product Tree in memory. Since avoiding creation of unneeded object is always recommended, we decide to remove duplicate element in the tree by singularizing them. This is possible because the product is Read Only and made of identical meta data keys, meta keys value.


Entropy and cardinality of meta data An Attribute may have an unlimited number of meta text (among other things), common meta data keys are “long”, and “short” and “help” text description in 4 languages (en_us, fr_ch, de_ch, it_ch), while this is not a problem in the database, this make the Product object tree size quite huge in the Product cache (containing Products Value Object). ..Counting some of them in database for example return stunning result. We found 60000 “long” texts which translate into 60000 String text keys and 60000 String text values (worst case scenario since texts values may not be all reusable). Reducing this number of Objects is done quite easily by not creating new instance of String, Decimal, Integer object and returning always the right and same Object instance. (we keep them in a MAP and return either a new instance or a previously cache one).

Large objects cardinality but a poor entropy By running two or three SQL statement and trying to distinguish real distinct values, we found that a lot of these meta data are made of a relative small number of different values. By just storing a limited number of String like “”, “1”, “2” to “99”, “default”, “long”, “short”, “de_ch”, “fr_ch” we have reach a cache efficiency and reuse of object instance of 99% After that “small” change in the way value objects (VO) are created and connected, a java String object containing before “de_ch” and existing 10000 times in memory is now replaced across all Attributes/Bricks by the same instance!

The gain is simply phenomenal. Memory gain is bigger than 50%.

Reducing the number of objects in memory Instead of storing thousands of Products Text String in memory, we decided to allocate them on disk using java reflection API and a Dynamic Proxy.

The idea is to save all String in one or more files on disk, the position of each text and length being saved in the corresponding Value Object. So basically we gain the space used by a String in memory at the expense of a long (String position in file relative to start of file) and an int (length of String) primitive type

References: ProxyInvocationHandler Resume: Java String disk based allocation Code snippet: soon

Use better data structures Java has a lot of quality library, commons collections from apache are well known. Javalution is a real time library with real time and reduce garbage collector impact. We have use FastTable and FastMap where it make sense.

For example the class FastTable has the following advantages over the widely used java.util.ArrayList:

  • No large array allocation (for large collections multi-dimensional arrays are employed). The garbage collector is not stressed with large chunk of memory to allocate (likely to trigger a full garbage collection due to memory fragmentation).
  • Support concurrent access/iteration without synchronization if the collection values are not removed/inserted

Different caching strategy By design the ProductCatalog is able to use many caching strategy. One is named “Nocache” limit number of object in memory to the bare minimum, and redirect all access to product to database. In a mono user environment, and since products reside in 4 tables only (so only 4 select to read all data from DB and some VO to rebuild the tree are needed), the through output is more than enough.

More to come

References

  • Java Performance Tuning Tips, resources, and monthly newsletter on improving the performance of applications.
  • Java Tuning White Paper The Java Tuning White Paper is the reference for Java Performance Tuning information, techniques and pointers.
  • Tomcat WIKI
  • Apache MyFaces WIKI

Related content

Junit tips and tricks

Thursday, Jan 28, 2021

Lots of Junit tips and tricks I used since its inception
4 minutes read

Apache POI contribution patches

Saturday, Jun 1, 2013

The [Apache POI][2] Project ’s mission is to create and maintain #Java APIs for manipulating various file formats based upon the Office Open XML standards (OOXML) and Microsoft ’s OLE 2 Compound Document format (OLE2). In short, you can read and write MS Excel files using #Java. In addition, you can read and write MS Word and MS PowerPoint files using #Java. [Apache POI][2] is your #Java Excel solution (for Excel 97-2008). We have a complete API for porting other OOXML and OLE2 formats and welcome others to participate.
3 minutes read

© 1997 - 2024 Cédric Walter blog

Powered by Open Sources technologies

avatar

Cédric WalterA true selfless act always sparks another

6s a1 acide-hyaluronique acma adaptability advocate-for-change ai airplane algorand alice-hlidkova-author alpine alps altruism-vs-commercialization antique-scooters antiseptic-rinse apache arcade arcade-gaming armattan art artemis artemis-viper artistic-expression atlassian authenticity-in-writing authenticity-matters avis bag bambulab bash bean bennu bernardet bestwishes betaflight betruger beware bien-vivre bien-être bien-être-physique bio bioethics bitcoin blessures-sportives blockchain blockchain-consensus-encyclopedia blockchain-systems blog book-review books bots Bought box brand-authenticity brand-integrity brand-protection breaking-barriers business-management business-milestones business-strategy business-success business-transformation businessbooks byzantine-fault-tolerance calculator calibre calibre-web camera case-studies cc2500 cgm-next challenges changement-de-vie channel-setup cheaper cherry-blossoms chirurgie-orthopédique choosing-fbl-gyro ci/cd classic-games classic-scooters classic-vespa climb climbing codefest collectible-scooters collectibles collection collector color competition consensus-algorithms consensus-mechanisms console consommation-responsable consumer-awareness containerization contest control-surfaces controller copy corticostéroïdes counterfeit-awareness counterfeit-culture counterfeit-market counterfeit-vs-authentic covid19 creating croissance-personnelle cryptocurrency cultural-experience cultural-richness curve-adjustments customer-discovery cve-issues dance-dreams death decentralization decentralized dental-hygiene dependency Design development devfest devops distributed-ledger-technology diverse-perspectives diy-dental diy-health dji docker docker-compose docker-hosting docker-networking docker-registry docker-security dont-buy dotnet Download downloading dreams-and-reality drone dynamic-ip désencombrement développement-personnel développement-spirituel ecology edgetx elrs elta emotional-challenges emotional-hurdles empowering-narrative endpoints engelberg Ensitm entrepreneurial-lessons entrepreneurial-mindset entrepreneurs entrepreneurship entrepreneurship-books Essaim essentially ethereum ethical-dilemmas evoque execution exercices-de-renforcement exercise-form facebook failure-analysis failure-stigma failure-to-success fake fake-apparel fake-brands fake-goods family family-building family-dynamics fashion-ethics fashion-fraud fbl-controllers fbl-system-compatibility fbl-system-features fbl-system-reviews fertility-struggles finance-books finances-personnelles financial-modeling financiallanning firearm firmware-customization firmware-issues fissure-horizontale fitness-routine fitness-tips flexibilité flight-controller flybarless-advantages flybarless-systems foss fpv frame France freestyle fresh-breath friendship-goals front gallery game-music gameplay-mechanics gamer-community games gaming-culture gaming-enthusiast gaming-history gaming-legacy gaming-nostalgia generative-ai genou gestion-de-ladouleur gestion-du-temps git global-impact google green-tea green-tea-mouthwash growth-hacking-books growth-mindset guide hackathon hackday hackfest health-and-wellness helicopter helicopter-community helicopter-gyro helicopter-tuning herbal-mouthwash hewlettpackard historical-scooters hobbies hobby hobbyist-blog holidays holistic-oralcare hollidays home-remedy home-workouts homelab homemade-oralcare honda honesty honey hornet how-to howTo https hugo human-connection hygiene-routine icecream iconic-scooters iflight iflightnazgulevoque immich indoor industrial-shit industry injections-intra-articulaires injury-prevention innovation innovation-books innovation-journey ios japan-travel japanese-cuisine jar java jdk11 jellyfin joint-health junit jupiter kitchen knee-rehabilitation knee-stability knockoff-alert kyoto lacoste lacoste-counterfeit lambretta landmarks leadership leadership-books lean-startup learning-from-failure leg-day leg-workouts legal-complexities legit-fashion let's-encrypt libération life-transformations link linux llm local-traditions m2evo macos magical-adventure magician-lord main make manurhin manurhin-sm75 mapping marathon market-research marketing-books maven me medical medical-advancements metakernel miami-entertainment mid-century-scooters migration mindset-shifts minimalisme minimum-viable-product minty-fresh mixer-settings mk3 mk4 mobilité model-setup modern-family modern-motherhood moon moral-encounters motherhood-dilemmas motorcycle mount mountain mountains mouth-rinse mouthwash-ingredients mouthwash-recipe Mulhouse muscle-activation music mvs mycollection ménisque NASA natural-mouthwash nature nazgul neo-geo-aes neogeo network new-bookrelease nginx-proxy north-face north-face-replica nostalgic-scooters nv14 objectifs old-school-scooters omphobby open-source open-source-rc opensource opentx openvpn oral-care oral-health organizer osaka oss overcoming-challenges p1p p1s parental-rights parenthood-reflections parts passion patella-health persistence personal-relationships photos physical-therapy physiothérapie pivot-strategy pixel-art planet plasma-riche-en-plaquettes platform plex pluto pretty-girl-complex privacy product-market-fit productivity-books proof-of-stake proof-of-work protect-your-style prusa prusa-research public-image quadcopter quadriceps-strength radio-control radio-programming radiomaster rare-scooters raspberrypi raspbian rates-configuration rc rc-community rc-configuration rc-firmware RC helicopter rc-helicopter-electronics rc-helicopter-enthusiasts rc-helicopter-setup rc-helicopter-technology rc-helicopter-tips rc-helicopters rc-modeling rc-simulator realdebrid realflight receiver reflex-xtr refreshing-breath rehabilitation-exercises relations-personnelles relationship-complexities released remote remote-control-flying reproductive-ethics resilience-in-business resilient-women restored-scooters retro-gaming retro-gaming-community retro-gaming-console retro-scooters reverse-proxy rhythms-of-life risk-management robotic router rx réadaptation rééducation sab sab-raw-420 sab-raw-580 sab-raw-700 sales-books santé-articulaire santé-mentale scooter-enthusiast scooter-memorabilia scooters security-nightmare self-leveling-helicopter server-configuration servo-config skydiving snk snk-corporation snk neo geo soap social-issues solex space spams sport ssl-termination ssl/tls startup-books startup-failure static-code-generator steam strategic-networking streaming strength-training success-stories sun support surrogacy-agency surrogacy-journey surrogacy-narratives swiftui swiss switzerland team team-building team-dynamics teeth-cleaning temples-and-shrines tendermint terrot thérapie-physique tokyo torvol traefik traitement-des-fissures transmitter transmitter-firmware travel travel-tips trouver-du-sens tunnel turning-setbacks-into-success tutorial tx unconventional-strategies vacation velosolex vespa viaferrata video video-game-review vintage vintage-scooters vintage-two-wheelers vintage-vespa vintagegaming vmo-exercises warez web-security wind winner winterthur women-supporting-women wordpress workout-progression x1c zurich zyxel zyxel-avoid zyxel-not-serious-with-security zyxel-outdated zyxel-router-not-good équilibre
Me

Cédric Walter is a French-Swiss entrepreneur, investor, and software engineer based in Zurich, Switzerland. He spent his career developing software applications for Swiss insurance companies to handle billions of dollars in premiums. He cofounded Innoveo AG and as the software architect developed the no-code platform designed to reduce the manual coding that powers many software apps. As an active participant in the European hacking community, he works on many open source projects including blockchain. Cédric is a winner of multiple hackathons. His expertise include designing back end, event-based, and blockchain systems. Cédric is also the founded Disruptr GmbH, a software development company that offers full spectrum of services for businesses of all sizes.

JAVA full-stack developer since 2000, in Blockchain since 2017, Certified Scrum Master 2012, Corda Certified Developer in 2019, Ethereum smart contract expert in the SWISS Blockchain Security working group

Hackathons

  • HackZurich 2022 – Level Up in top 25 finalist among 134 submissions
  • SBHACK21 – SwiFi winner of best Solution on Algorand, overall Winner 3rd Prize, CV Labs Fast Track Ticket
  • HackZurich 2020 Europe’s Biggest Hackathon winner in category Migros
  • SBHACK19 – LendIt winner of Swiss biggest Blockchain Hackathon. On chain insurance and ledger for agricultural land soil.
  • Member of the Bitcoin Association Switzerland and Cryptovalley association Switzerland,

PGP: DF52 ADDA C81A 08A6

Copyright information

All editorial content and graphics on our sites are protected by U.S. copyright, international treaties, and other applicable copyright laws and may not be copied without the express permission of Cedric Walter, which reserves all rights. Reuse of any of Cedric Walter editorial content and graphics for any purpose without The author ’s permission is strictly prohibited.

DO NOT copy or adapt the HTML or other code that this site creates to generate pages. It also is covered by copyright.

Reproduction without explicit permission is prohibited. All Rights Reserved. All photos remain copyright © their rightful owners. No copyright infringement is intended.

Disclaimer: The editor(s) reserve the right to edit any comments that are found to be abusive, offensive, contain profanity, serves as spam, is largely self-promotional, or displaying attempts to harbour irrelevant text links for any purpose.

Others

If you like my work or find it helpful, please consider buying me a cup of coffee ☕️. It inspires me to create and maintain more projects in the future. 🦾

It is better to attach some information or leave a message so that I can record the donation 📝 , thank you very much 🙏.

Reproduction without explicit permission is prohibited. All Rights Reserved. All photos remain copyright © their rightful owners. No copyright infringement is intended.