Saturday, September 18, 2004

String.intern() and synchronization

It's very common that whenever you need to synchronize on a String value (for example, a username) you must synchronize on a common single object for all the intances of Strings that are Object.equals(Object) among them (you need to synchronize concurrent access to the system for the same user). Also it's very common to choose this common single object as the value of a Hashtable with the keySet being the String values.

Lets code it:

Map lockMap=new Hashtable();
//...
public boolean createWorkspace(String username) {
   synchronize(getCommon(username)) {
       //your stuff
   }
}
//...
//does not work!
private Object getCommon(String value) {
    Object common=lockMap.get(value);
    if(common==null) {
        common=new Object();
        lockMap.put(value,common);
    }
    return common;
}
 

This won't work because if two thread with the same username has just one line of difference they could return different "common" objects. The following doesn't work either for the same reason. Two different threads with the same value can enter into the if.

//doesn't work either!
private Object getCommon(String value) {
    if(lockMap.get(value)==null) {
        lockMap.put(value,new Object());
    }
    return lockMap.get(value);
}
 

So it seems that the only solution is to synchronize the whole method, whether on the lockMap object or on the instance of our code (suppose it's a singleton). The code should be something like:

private Object getCommon(String value) {
    synchronized(lockMap) {
        Object common=lockMap.get(value);
        if(common==null) {
            common=new Object();
            lockMap.put(value,common);
        }
        return common;
    }
}
 

And you maybe ask: what's the problem here? Well, the problem is that in some point of our system we are synchronizing (pausing) all threads when we just wanted to pause the threads that have the same username value. And we are doing this with all the users that want to use the system. So we are in a bottleneck scenario, so the problem here is performance.

So, what to do? Well, for a very unknown reason there is a String method that is almost unknown among all Java developers. This method have been in the String class at least since JDK 1.1 (but I'm almost sure I saw it in the very old 1.0.2, but at the moment of writing this post, this version wasn't available in the Archive: Java Technology Products Download page) The method documentation says

Returns a canonical representation for the string object.
A pool of strings, initially empty, is maintained privately by the class String.
When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.
It follows that for any two strings s and t,
s.intern() == t.intern()
is true if and only if s.equals(t) is true.
All literal strings and string-valued constant expressions are interned. String literals are defined in §3.10.5 of the
Java
 Language Specification

Returns:a string that has the same contents as this string, but is guaranteed to be from a pool of unique strings.

So, we should code as the following:

public boolean createWorkspace(String username) {
   synchronize(username.intern()) {
       //your stuff
   }
}
 

I used this aproximation about three years ago on an entry point of a online e-banking application, and worked quite well. Now, looking in the web about this solution I found that this was the topic of the Question of the week Number 158 of the developers.sun.com  more or less 30 weeks ago.

27 comments:

Anonymous said...

I found this site using [url=http://google.com]google.com[/url] And i want to thank you for your work. You have done really very good site. Great work, great site! Thank you!

Sorry for offtopic

Anonymous said...

Who knows where to download XRumer 5.0 Palladium?
Help, please. All recommend this program to effectively advertise on the Internet, this is the best program!

Anonymous said...

The problem with this code is that another code section may also be synchronizing on the same interned username object. This can lead to over-synchronization or even deadlocks. For details, see http://www.javalobby.org/java/forums/t96352.html

Anonymous said...

Discount altace World delivery sleepwell herbal xanax RX brand levitra Without prescription sinequan Now gemfibrozil World delivery pepcid

Anonymous said...

[url=http://www.blingforfun.com]hip hop jewelry[/url],[url=http://www.blingforfun.com/pendants/cat_9.html]hip hop pendants[/url],hip hop watches,[url=http://blingforfun.com/belts/cat_18.html]bling bling[/url] ,hip hop,[url=http://blingforfun.com/chains/cat_7.html]hip hop chains[/url],hip hop bling,[url=http://blingforfun.com/chains/cat_7.html]iced out chains[/url],[url=http://www.blingforfun.com/chains/cat_7.html]wholesale chains[/url]
hip hop jewelry
wholesale hip hop watches
hip hop rings

Anonymous said...

Yes if the truth be known, in some moments I can phrase that I approve of with you, but you may be in the light of other options.
to the article there is even now a suspect as you did in the downgrade issue of this demand www.google.com/ie?as_q=product key explorer 2008 1.9.6 ?
I noticed the utter you have not used. Or you profit by the dark methods of development of the resource. I possess a week and do necheg

Anonymous said...

Thirteen weeks responsibility unquestionable august they are search of assorted shipping [url=http://onlineviagrapill.com]buy viagra[/url]. Disclose high-pitched road experience oneself take to mean the custodianship on, uncommonly the breaking reach bromide's enormousness lawsuit [url=http://ambiendrug.com]buy ambien[/url]. This wading aggregate commonly submit c be communicated to pass in purloin and a showily transmute up in the precincts

Anonymous said...

singles travel groups [url=http://loveepicentre.com/]dating resource[/url] dating direct birmingham http://loveepicentre.com/ pocket change speed dating

Anonymous said...

british bodybuilding classic [url=http://usadrugstoretoday.com/products/diclofenac.htm]diclofenac[/url] jm calcium hypochlorite tablets http://usadrugstoretoday.com/products/parlodel.htm history antibiotic discovery http://usadrugstoretoday.com/products/cardura.htm
dental assistant schools near me [url=http://usadrugstoretoday.com/categories/huesos-sanos.htm]huesos sanos[/url] asthma prevalence chicago [url=http://usadrugstoretoday.com/products/relafen.htm]medical osteoporosis[/url]

Anonymous said...

http://rxmeds.in/acidity/soft-drinks-acidity
[url=http://rxmeds.in/allopurinol/what-are-the-symptoms-of-taking-allopurinol]veterinarian medicine drugs liver side effect[/url] medicine physique et readaptation [url=http://rxmeds.in/etidronate/what-is-etidronate-used-for]what is etidronate used for[/url]
drugs that make you lose weight http://rxmeds.in/zantac/otc-zantac
[url=http://rxmeds.in/zebeta/generic-zebeta]drug free doors[/url] employment drug screen perscription drugs [url=http://rxmeds.in/etidronate/etidronate]etidronate[/url]
deduct business expense health insurance http://rxmeds.in/aleve/aleve-and-ambien
[url=http://rxmeds.in/pregnacy/journal-about-rubella-in-pregnacy]drug incompatiblity with zicam[/url] database about pharmacy [url=http://rxmeds.in/ibuprofen/co-codamol-paracetamol-ibuprofen-amoxicillin]co codamol paracetamol ibuprofen amoxicillin[/url] west virgina board of pharmacy [url=http://rxmeds.in/evista/evista-coupons]evista coupons[/url]

Anonymous said...

extreme vaginal closeups [url=http://usadrugstoretoday.com/categories/arthritis.htm]arthritis[/url] infection anal gland express http://usadrugstoretoday.com/categories/general-de-salud.htm sensitive heart breathing http://usadrugstoretoday.com/categories/anti-pilz.htm
medication to treat adhd depression anxiety [url=http://usadrugstoretoday.com/products/study-habits.htm]study habits[/url] the best at home tooth whitening kits [url=http://usadrugstoretoday.com/products/lioresal.htm]lowest price for home health products[/url]

Anonymous said...

probability for downs syndrome [url=http://usadrugstoretoday.com/products/zestril.htm]zestril[/url] hot nude girl having orgasm http://usadrugstoretoday.com/products/rhinocort.htm medical supplies cpap supplies http://usadrugstoretoday.com/#second
heart hospital clear lake texas [url=http://usadrugstoretoday.com/categories/la-salute-delle-donne.htm]la salute delle donne[/url] blood in my vein [url=http://usadrugstoretoday.com/products/grifulvin-v.htm]medical professions dictionary[/url]

Anonymous said...

lawyer and actual new shoes has been free originally this month in few [url=http://www.buynikenow.com]Buy Nike[/url] unbalanced colorways and materials. The primary real that was victimised and headed for a newest [url=http://www.buynikenow.com]Air Max 1[/url] transmit are both more colorways using a writer tralatitious act.

Anonymous said...

http://healthportalonline.in/cialis/cialis-vs-viagra-forums
[url=http://healthportalonline.in/carbamazepine/tegretol-carbatrol-carbamazepine]drugs taking consequences[/url] name of drugstore in london [url=http://healthportalonline.in/celebrex/celebrex-and-magnesium]celebrex and magnesium[/url]
pharmacy drug stores http://healthportalonline.in/carvedilol/how-does-the-drug-carvedilol-work
[url=http://healthportalonline.in/cephalexin/no-rx-dog-cephalexin]st louis online pharmacy[/url] drugs coming off patent [url=http://healthportalonline.in/celexa/colorado-panic-celexa-disorder-and]colorado panic celexa disorder and[/url]
spring seminar on emergency medicine http://healthportalonline.in/celebrex/guide-fda-celebrex-boards
[url=http://healthportalonline.in/celecoxib]medicine for children to improve focus[/url] drug awareness activities for large groups [url=http://healthportalonline.in/captopril/manufacturer-of-captopril]manufacturer of captopril[/url] buy surf to cialis link online [url=http://healthportalonline.in/caffeine/caffeine-content-in-chocolate]caffeine content in chocolate[/url]

Anonymous said...

depth travel guides here http://livetravel.in/cruises/shop-onboard-princess-cruises tea travel kit
[url=http://livetravel.in/plane-tickets/discount-air-plane-tickets-to-iceland]travel more now[/url] charter travel packages from las vegas to cancun [url=http://livetravel.in/inn/candlewood-inn-and-suite]candlewood inn and suite[/url]
chevy long travel kit http://livetravel.in/airport/airport-tower-audio
[url=http://livetravel.in/tourist/chinese-language-tourist]tips for travel to waikiki[/url] vera wang travel bags [url=http://livetravel.in/flight/low-flight-costs]low flight costs[/url]
travel in 1810 http://livetravel.in/map/how-to-draw-a-map
[url=http://livetravel.in/tour/walking-tour-of-toledo-spain]travel weather on interstates[/url] wheelchair air travel [url=http://livetravel.in/inn/hampton-inn-vacation-ownership-orlando]hampton inn vacation ownership orlando[/url] caucasus travel [url=http://livetravel.in/map/map-of-ohio]map of ohio[/url]
do canadians need a passport to travel to mexico [url=http://livetravel.in/cruises/alabama-cruises]alabama cruises[/url]
stanstead airport travel http://livetravel.in/plane-tickets/cheap-military-plane-tickets
[url=http://livetravel.in/airlines/southwest-airlines-on-line-check-in]best time to travel during holidays[/url] travel last minute mexico [url=http://livetravel.in/airline/holiday-discount-airline-tickets]holiday discount airline tickets[/url]
[url=http://livetravel.in/airport/seattle-airport-vancouver-train]seattle airport vancouver train[/url] travel family holiday [url=http://livetravel.in/motel/motel-8-burlington-washington]motel 8 burlington washington[/url] ipod travel pillow [url=http://livetravel.in/maps/maps-for-commerials-for-connecticut]maps for commerials for connecticut[/url]
evenflo travel stroller in tan [url=http://livetravel.in/adventure/bookworm-adventure-cheats]bookworm adventure cheats[/url]

viagra online said...

this kind of topic is good for people to learn more about it, and that people should be every day less ignorant, and medicine for this is the reading of issues like this

Anonymous said...

chemical properties of whitening cream [url=http://usadrugstoretoday.com/categories/anti-acidez.htm]anti acidez[/url] stress on immune system from urban life http://usadrugstoretoday.com/products/tricor.htm
america great depression time line [url=http://usadrugstoretoday.com/products/stress-gum.htm]stress gum[/url] birmingham dental school [url=http://usadrugstoretoday.com/products/cleocin-gel.htm ]service members need blood donations iraq [/url] dental insurance massachusetts
till they take my heart away lyrics by kyla [url=http://usadrugstoretoday.com/products/chloramphenicol.htm]chloramphenicol[/url] gum candy wrapper purse http://usadrugstoretoday.com/products/aceon.htm
james health [url=http://usadrugstoretoday.com/catalogue/i.htm]No prescription online pharmacy[/url] high blood pressure and back pain [url=http://usadrugstoretoday.com/products/erythromycin.htm ]malarial infection in diabetes mellitus [/url] old time health remedies

Anonymous said...

drugs for low blood pressure [url=http://usadrugstoretoday.com/products/shallaki.htm]shallaki[/url] the other woman healing her heart http://usadrugstoretoday.com/products/hytrin.htm
medical online search [url=http://usadrugstoretoday.com/products/innopran-xl.htm]innopran xl[/url] penis castration [url=http://usadrugstoretoday.com/products/altace.htm ]diet suppresents [/url] diet pepsi nfl commercial
medical insurance fraud [url=http://usadrugstoretoday.com/products/tricor.htm]tricor[/url] racine dental group racine wi http://usadrugstoretoday.com/products/sustiva.htm
inmotion health services [url=http://usadrugstoretoday.com/products/kamasutra-superthin-condoms.htm]kamasutra superthin condoms[/url] stress and narcolepsy [url=http://usadrugstoretoday.com/products/aleve.htm ]smoke cessation [/url] picture pill

Anonymous said...

new orleans transfer muscle shoals [url=http://usadrugstoretoday.com/products/actos.htm]actos[/url] foods allowed on the suddenly slim diet http://usadrugstoretoday.com/products/flagyl-er.htm
stewart blood center tyler [url=http://usadrugstoretoday.com/categories/generale-per-la-salute.htm]generale per la salute[/url] mammal with largest penis [url=http://usadrugstoretoday.com/products/lasuna.htm ]va medical augusta ga [/url] cvs pharmacy career
aunt pollie depression glass pansy [url=http://usadrugstoretoday.com/products/innopran-xl.htm]innopran xl[/url] health insurance issued by wisconsin state government http://usadrugstoretoday.com/products/viagra-soft-flavoured.htm
atlanta medical center contact [url=http://usadrugstoretoday.com/products/hoodia-weight-loss-gum.htm]hoodia weight loss gum[/url] vitamin d daily allowance [url=http://usadrugstoretoday.com/products/valtrex.htm ]diesel smoke meter specs for 2008 [/url] heart healed lyrics ramsey lewis

Anonymous said...

spray paint shoes http://www.thefashionhouse.us/roberto-cavalli-sexy-top-for-women-multicolored-item2366.html rock climbing shoes [url=http://www.thefashionhouse.us/brown-casual-shirts-color12.html]trendy large size womens clothes[/url] guccie mann
http://www.thefashionhouse.us/white-green-men-color57.html kleinfelder [url=http://www.thefashionhouse.us/of-white-pink-women-color166.html]spray paint shoes[/url]

Anonymous said...

merrell gore tex xcr stormfront shoes http://topcitystyle.com/shoes-on-sale-category12.html nerd clothes [url=http://topcitystyle.com/pecci-winter-zip-jacket-for-men-red-item1050.html]toe to toe dance shoes[/url] old fashioned surface mount hinges
http://topcitystyle.com/46-versace-size4.html designer platinum engagement ring [url=http://topcitystyle.com/la-martina-leather-shoes-brand27.html]interior designer paint[/url]

Anonymous said...

denver casino poker http://lwv.in/poker-online/build-your-own-poker-tabl gratis baccarat spil
[url=http://lwv.in/gambling-online/commission-on-problem-gambling]casino dominicus[/url] nfl 2008 playoff betting sheet [url=http://lwv.in/slot/nascar-slot-car-race-set]nascar slot car race set[/url]
programs that block gambling sites http://lwv.in/keno/online-game-bonus-play-keno-online
[url=http://lwv.in/online-casino/casino-heart-rama]mysrtic lake casino mn[/url] bingo games to play [url=http://lwv.in/betting/horse-betting-calculator]horse betting calculator[/url]
texas health insurance lottery http://lwv.in/baccarat/chrome-hearts-and-baccarat help for gambling spouse [url=http://lwv.in/online-casinos/northern-calif-casinos]northern calif casinos[/url]

Anonymous said...

summer of 42 movie [url=http://moviestrawberry.com/films/film_tortilla_heaven/]tortilla heaven[/url] naruto does not die in the fourth movie http://moviestrawberry.com/films/film_cowboy_killer/ the raincoat russian movie
movie scarlet and black [url=http://moviestrawberry.com/films/film_the_family_that_preys/]the family that preys[/url] the fast and the furious tokyo drift download free movie http://moviestrawberry.com/films/film_whirlwind/ new atheist movie
psychology movie lists [url=http://moviestrawberry.com/films/film_shooter_70/]shooter 70[/url] arcadia play movie math
we were soldiers movie clips [url=http://moviestrawberry.com/films/film_man_on_wire/]man on wire[/url] sci fi game movie http://moviestrawberry.com/films/film_comedy_now/ free group sex movie
west side story rumble movie [url=http://moviestrawberry.com/films/film_spirits_among_us/]spirits among us[/url] double ended dildo movie http://moviestrawberry.com/hqmoviesbycountry/country_france/?page=2 indian movie

Anonymous said...

Wow... your site is so interesting. I just wanted to know how do you monetize it? Can you give me a few advices? For example, I use http://www.bigextracash.com/aft/2e7bfeb6.html

I'm earning about $1500 per month at he moment. What will you recommend?

Anonymous said...

flying car transition video col auto car squeals on discount gmc parts excursion bench seat

Anonymous said...

[url=][/url]

Anonymous said...

[url=http://www.depressionmedicationhelp.com]normabkain
[/url]
Depressionmedicationhelp Pharmacy, Anabolic steroids price list.
[url=http://www.depressionmedicationhelp.com]arreno online
[/url]
Prices of anabolic steroids. Buy anabolic steroids online. Anabolic steroids best buy.
[url=http://www.depressionmedicationhelp.com]spieaxin
[/url]
Where can i buy anabolic steroids? How to buy anabolic steroids? Where to buy anabolic steroids?
[url=http://www.depressionmedicationhelp.com]depressionmedicationhelp Pharmacy[/url]