Sunday, September 21, 2008

What is a Memoizer and why should you care about it?

A Memoizer is a class created by Doug Lea/Brian Goetz. It's basically a create-and-store cache. That is, it has one very useful property:


  • A Memoizer is a Generic class that encapsulates the process of creating a value, and remembering the value (memoizing it) so that subsequent calls to get the value will return the memoized value, and not call the Factory method to create it.

Why do you care?

  • A Memoizer encapsulates the process of "getOrCreate()" which is highly useful when you are getting a resource that does not change by a key (think cache) and which is generally considered to be expensive to create.

But, you ask, I already can do that, why do I need a Memoizer? Glad you should ask. Memoizer is unique in its solution, because it caches a value by key, but its implementation is very efficient. It has the following additional properties:

  1. Calls to get items are concurrent

  2. Calls to get items for a particular key are guaranteed to call the Factory method for that key once and only once


It's important to understand that what the Memoizer does is both efficient, and correct. It's relatively easy to roll your own "getOrCreate()" method that has only one of those properties (and most people do). It's not so easy - or obvious - to do both and that's why you should use a Memoizer - and not roll your own.

To review, let's see the strategy most people would use for calling the Factory method once and only once. Here's how to call the Factory method once and only once:

/*** SUB OPTIMAL IMPLEMENTATION THAT IS CORRECT, BUT NOT CONCURRENT ***/
private final Factory<A,V> factory = ...;
private final Map<A, V> map = new HashMap<A, V>();

public V getOrCreate(A key) {
synchronized (map) {
if (map.contains(key)) { return map.get(key); }

// create
V value = factory.create(key);
map.put(key, value);
return value;
}
}

But of course, the line synchronized (map) should be a tip-off that this implementation is not concurrent
since there is only a single lock protecting access to our map. Can we do better? Sure. Let's use a ConcurrentHashMap to make our getOrCreate() method concurrent (but as we'll see, will not have the once-and-only-once property):

/*** SUB OPTIMAL IMPLEMENTATION THAT IS CONCURRENT, BUT NOT CORRECT ***/
private final Factory<A,V> factory = ...;
private final ConcurrentMap<A, V> map = new ConcurrentHashMap<A, V>();

public V getOrCreate(A key) {
if map.contains(key) { return map.get(key); }

// map doesn't contain key, create one -- note that first writer wins,
// all others just throw away their value
map.putIfAbsent(key, Factory.create(key));

// return the value that won
return map.get(key);
}

So, those are the two implementations, each implements either correctness (once and only once) or performance (concurrent puts and gets) but neither accomplishes both simultaneously. Of course, that's the whole point of this article. To introduce you to Memoizer. So how does Memoizer ensure correctness (once and only once) while being simultaneously concurrent?

The trick is to delay the call to the Factory create method into the future. We already know how to make the operation concurrent, but making the operation concurrent means that the first writer will win, and all the other writers will lose. So we delay the Factory create call by wrapping that call in a FutureTask. In other words, instead of putting the actual value into the map, we put a Future (which is a wrapper for getting the value sometime in the future) into the Map.

(Note: If you have not yet become familiar with the Future and FutureTask classes introduced in the JDK 1.5, you should)

By putting a Future into the map - and not our actual value - we can move the work of calling the Factory create method into the future - specifically we can move it until after the winner of the race to put the value into the map has been determined. That enables us to call get - which calls create on the Factory - on the one and only Future instance that is contained within the Map.

The full code for Memoizer illustrates this trick. Note that the Computable interface specifies a generic "Factory". Also note that I have not been able to find a library or canonical reference for Memoizer. The best I have is here: Memoizer.java.

Here it is re-created for your convenience (note that I have adjusted it slightly, for example allowing the user to specify the number of segments created in the underlying ConcurrentHashMap):

public interface Computable<A, V>
{
V compute(A arg) throws InterruptedException;
}

public class Memoizer<A, V> implements Computable<A, V>
{
private final ConcurrentMap<A, Future<V>> cache;
private final Computable<A, V> c;

public Memoizer(Computable<A, V> c)
{
this(c, 16);
}

public Memoizer(Computable<A, V> c, int segments)
{
this.cache = new ConcurrentHashMap<A, Future<V>>();
this.c = c;
}

public V compute(final A arg) throws InterruptedException
{
while (true) {
Future<V> f = cache.get(arg);
if (f == null) {
Callable<V> eval = new Callable<V>() {
public V call() throws InterruptedException {
return c.compute(arg);
}
};
FutureTask<V> ft = new FutureTask<V>(eval);
f = cache.putIfAbsent(arg, ft);
if (f == null) {
f = ft;
ft.run();
}
}
try {
return f.get();
} catch (CancellationException e) {
cache.remove(arg, f);
} catch (ExecutionException e) {
LaunderThrowable.launderThrowable(e);
}
}
}
}

You will of course need the LaunderThrowable implementation to compile this example. For a full code listing, hop on over to Terracotta, where I show not only a full working example, but demonstrate how it works with Terracotta across two nodes:

Full Memoizer Example with Terracotta

28 comments:

Khalil said...

Couple of comments: Does the Memoizer have a clear/reset method to clear the cache and allow values to be GCed, couldn't the ConcurrentMap in the Memoizer implementation be a ConcurrentReferenceMap, secondly how would you deal with multiple arguments, varargs? or box them in an array like structure with equals and hashCode support.

Cheers,
Khalil

Buddy Casino said...

I played around with the Memoizer once, and it lacks a mechanism to expire items and/or limit the bumber of entries.
Basically, it's just a example of a concurrent caching pattern done right, not a full-blown caching solution.

I don't feel confident implementing those missing features, as I'm pretty sure to screw up the concurrency issues in a subtle way. Has anyone else gotten around to do that?

Alex Miller said...

This reminded me of this link (from Doug Lea) on lazy map initialization, which is a separate but related topic:

http://artisans-serverintellect-com.si-eioswww6.com/default.asp?W122

Taylor said...

@Khalil and buddy casino

I agree, as written there is no remove. I've thought through the process of remove delegation to the CHM should be just fine, and I in fact had implemented remove in a version of the Memoizer I use (I elided it for simplicity here, I suppose I shouldn't have).

So, remove would be just:

public V remove(final A arg)
{
return cache.remove(arg);
}

mario.gleichmann said...

Nice post!

... but hmmm, did i miss something, or is your example not exactly the one from within the book 'Java Concurrency in Practice' ?

Greetings

Mario Gleichmann

Taylor said...

@mario,

No, you are right, it's not the same - I found a reference from the concurrency mailing list.

I've also begun to make my own modifications, as I noted, one of them is to control the # of segments in the backing CHM. Another, which I removed, is to implement the remove method.

Ben said...

Coincidentally, I put up a decorator implementation last night due to a user request of my library. Combined, this provides an ad-hoc cache per Buddy's concern.
http://code.google.com/p/concurrentlinkedhashmap/wiki/SelfPopulatingCache

Buddy Casino said...

Thanks for sharing this, Ben! Didn't expect that, looks great.

said...

A片,A片,成人網站,成人漫畫,色情,情色網,情色,AV,AV女優,成人影城,成人,色情A片,日本AV,免費成人影片,成人影片,SEX,免費A片,A片下載,免費A片下載,做愛,情色A片,色情影片,H漫,A漫,18成人

a片,色情影片,情色電影,a片,色情,情色網,情色,av,av女優,成人影城,成人,色情a片,日本av,免費成人影片,成人影片,情色a片,sex,免費a片,a片下載,免費a片下載

情趣用品,情趣用品,情趣,情趣,情趣用品,情趣用品,情趣,情趣,情趣用品,情趣用品,情趣,情趣

A片,A片,A片下載,做愛,成人電影,.18成人,日本A片,情色小說,情色電影,成人影城,自拍,情色論壇,成人論壇,情色貼圖,情色,免費A片,成人,成人網站,成人圖片,AV女優,成人光碟,色情,色情影片,免費A片下載,SEX,AV,色情網站,本土自拍,性愛,成人影片,情色文學,成人文章,成人圖片區,成人貼圖

交友,AIO交友愛情館,AIO,成人交友,愛情公寓,做愛影片,做愛,性愛,微風成人區,微風成人,嘟嘟成人網,成人影片,成人,成人貼圖,18成人,成人圖片區,成人圖片,成人影城,成人小說,成人文章,成人網站,成人論壇,情色貼圖,色情貼圖,色情A片,A片,色情小說,情色小說,情色文學,寄情築園小遊戲, 情色A片,色情影片,AV女優,AV,A漫,免費A片,A片下載

coco0610 said...

wholesale jewelry
wholesale handmade jewelry
wholesale fashion jewelry
wholesale costume jewelry
handmade jewelry
fashion jewelry
costume jewelry
jewelry wholesale
wholesale pearl
wholesale crystal
discount jewelry
cheap jewelry
china jewelry wholesaler
wholesale china jewelry
handcrafted jewelry
wholesale jewellery
wholesale turquoise
wholesale swarovski
wholesale gemstone
wholesale coral
wholesale shell

漢美女 said...

(法新社a倫敦二B十WE四日電) 「情色二零零七」情趣產品大產自二十三日起在倫敦的肯辛頓奧林匹亞展覽館舉成人電影行,倫敦成人電影人擺脫對性的保守態度踴躍參觀,許多穿皮衣與塑膠緊身衣的好色之徒擠進這項成人網站世界規模最大的成人生活展,估計三天展期可吸引八萬多好奇民眾參觀。色情

活動計畫負責人a片下載米里根承諾:「要搞浪漫、誘惑人、玩虐待,你渴望的我們都有。」
成人網站
他說:「時髦的設計成人影片與華麗女裝,從吊飾到束腹到真人大小的雕塑,是我們由a片今年展出的數千件產品精av選出的一部分,A片下載參展產品還包括時尚服飾、貼身女用內在美、鞋子、珠寶、玩具、影片、藝術av女優成人影片圖書及遊戲,更不要說性愛輔具及馬術裝備。」
色情
參觀民眾遊覽情色電影A片百五十多個攤位,有性感服AV裝、玩具a片及情色食品,迎合各種品味。

情色大舞台上表演的是美國野蠻搖滾歌手瑪莉蓮曼森的前妻─情色電影全世色情影片界頭牌脫衣舞孃黛塔范提思,這是她今年在英情色國唯一一場表演。

以一九四零年代風格演出的黛塔范提思表演性感的天堂鳥、旋轉木馬及羽扇等舞蹈AV女優

參展攤位有的推廣情趣用品,有的公開展示人體藝術和人體雕塑,也有情色藝術家工會成員提供建議。

fds said...

导热油炉
导热油炉锅
导热油炉锅
转盘轴承
回转支承
转盘轴承
slewing ring
slewing bearing
slewing bearings
slewing bearing
slewing bearings

Benetton said...

牙醫,植牙,假牙|矯正|牙周病,牙醫診所植牙,紋身,刺青,TATTOO,皮膚科,痘痘,雷射脈衝光除斑,洗包包|洗鞋子|清洗包包,中醫,糖尿病,飛梭雷射,肉毒桿菌,玻尿酸,痘痘,脈衝光,醫美,seo,關鍵字行銷,關鍵字自然排序,網路行銷,關鍵字自然排序,關鍵字行銷seo,關鍵字廣告,網路行銷,seo,關鍵字行銷,關鍵字廣告,關鍵字,自然排序,部落格行銷,網路行銷,網路爆紅

dsfgsdfgsdfgds said...

看房子,買房子,建商自售,自售,台北新成屋,台北豪宅,新成屋,豪宅,美髮儀器,美髮,儀器,髮型,EMBA,MBA,學位,EMBA,專業認證,認證課程,博士學位,DBA,PHD,在職進修,碩士學位,推廣教育,DBA,進修課程,碩士學位,網路廣告,關鍵字廣告,關鍵字,廣告,課程介紹,學分班,文憑,牛樟芝,段木,牛樟菇,日式料理, 台北居酒屋,燒肉,結婚,婚宴場地,推車飲茶,港式點心,尾牙春酒,台北住宿,國內訂房,台北HOTEL,台北婚宴,飯店優惠,台北結婚,婚宴場地,推車飲茶,港式點心,尾牙春酒,住宿,訂房,HOTEL,飯店,造型系列,學位,牛樟芝,腦磷脂,磷脂絲胺酸,SEO,婚宴,捷運,學區,美髮,儀器,髮型,牛樟芝,腦磷脂,磷脂絲胺酸,看房子,買房子,建商自售,自售,房子,捷運,學區,台北新成屋,台北豪宅,新成屋,豪宅,學位,碩士學位,進修,在職進修, 課程,教育,學位,證照,mba,文憑,學分班,網路廣告,關鍵字廣告,關鍵字,SEO,关键词,网络广告,关键词广告,SEO,关键词,网络广告,关键词广告,SEO,台北住宿,國內訂房,台北HOTEL,台北婚宴,飯店優惠,住宿,訂房,HOTEL,飯店,婚宴,台北住宿,國內訂房,台北HOTEL,台北婚宴,飯店優惠,住宿,訂房,HOTEL,飯店,婚宴,台北住宿,國內訂房,台北HOTEL,台北婚宴,飯店優惠,住宿,訂房,HOTEL,飯店,婚宴,結婚,婚宴場地,推車飲茶,港式點心,尾牙春酒,台北結婚,婚宴場地,推車飲茶,港式點心,尾牙春酒,結婚,婚宴場地,推車飲茶,港式點心,尾牙春酒,台北結婚,婚宴場地,推車飲茶,港式點心,尾牙春酒,結婚,婚宴場地,推車飲茶,港式點心,尾牙春酒,台北結婚,婚宴場地,推車飲茶,港式點心,尾牙春酒,居酒屋,燒烤,美髮,儀器,髮型,美髮,儀器,髮型,美髮,儀器,髮型,美髮,儀器,髮型,小套房,小套房,進修,在職進修,留學,證照,MBA,EMBA,留學,MBA,EMBA,留學,進修,在職進修,牛樟芝,段木,牛樟菇,住宿,民宿,飯宿,旅遊,住宿,民宿,飯宿,旅遊,住宿,民宿,飯宿,旅遊,住宿,民宿,飯宿,旅遊,住宿,民宿,飯宿,旅遊,住宿,民宿,飯宿,旅遊,住宿,民宿,飯宿,旅遊,美容,美髮,整形,造型,美容,美髮,整形,造型,美容,美髮,整形,造型,美容,美髮,整形,造型,美容,美髮,整形,造型,美容,美髮,整形,造型,美容,美髮,整形,造型,設計,室內設計,裝潢,房地產,設計,室內設計,裝潢,房地產,設計,室內設計,裝潢,房地產,設計,室內設計,裝潢,房地產,設計,室內設計,裝潢,房地產,設計,室內設計,裝潢,房地產,設計,室內設計,裝潢,房地產,設計,室內設計,裝潢,房地產,進修,在職進修,MBA,EMBA,進修,在職進修,MBA,EMBA,進修,在職進修,MBA,EMBA,進修,在職進修,MBA,EMBA,進修,在職進修,MBA,EMBA,進修,在職進修,MBA,EMBA,進修,在職進修,MBA,EMBA,住宿,民宿,飯店,旅遊,美容,美髮,整形,造型,設計,室內設計,裝潢,房地產,進修,在職進修,MBA,EMBA,關鍵字排名,網路行銷,关键词排名,网络营销,網路行銷,關鍵字排名,关键词排名,网络营销,羅志祥,周杰倫,五月天,蔡依林,林志玲,羅志祥,周杰倫,五月天,蔡依林,林志玲,PMP,在職專班,研究所在職專班,碩士在職專班,PMP,證照,在職專班,研究所在職專班,碩士在職專班,網頁設計,網站設計,網頁設計,網站設計,网页设计,网站设计,网站设计,网页设计

KO said...

牙醫,植牙,假牙|矯正|牙周病,牙醫診所植牙,紋身,刺青,創業,批發,TATTOO,皮膚科,痘痘,雷射脈衝光除斑,中醫,腫瘤,腎臟病,僵直性脊椎炎,飛梭雷射,肉毒桿菌,玻尿酸,痘痘,脈衝光,醫美,毛孔粗大,醫學美容,seo,關鍵字行銷,關鍵字自然排序,網路行銷

,關鍵字自然排序,關鍵字行銷seo,關鍵字廣告

,網路行銷

,seo,關鍵字行銷,關鍵字廣告,關鍵字,自然排序,部落格行銷,網路行銷,網路爆紅,牛舌餅婚紗台中婚紗腫瘤腎臟病

kiloi said...

mens clothing men's sweate, cheap columbia jackets, lacoste sweater, ralph lauren polo shirts,ski clothing. Free Shipping, PayPal Payment. Enjoy your shopping experience on mensclothingstore.us

kiloi said...

nike tnEnter the necessary language
translation, up to 200 bytes winter, moves frequently in Chinanike chaussures showing that the deep strategy of the Chinese market. Harvard Business School, tn chaussures according to the relevant survey data show that in recent years the Chinese market three brands, Adidas, Li Ning market share at 21 percent, respectively,

kiloi said...

cheap polos
polo shirts
ralph lauren polo shirtssport shoes
ugg boots
puma shoes
chaussures pumamp4
trade chinalacoste polo shirts
chaussure puma femmewedding dressestennis racket
cheap handbags
HAIR STRAIGHTENERS
ED HARDY SHIRTS

kiloi said...

HAIR STRAIGHTENERS
MENSCLOTHING mans clothing
cheap ugg boots
converse shoes
wedding dresses
wholesale polo shirts
brand clothingcheap clothing
clothes sportspolos shirtair shoesair shoesed hardy clothinged hardy clothing
英文推广

kiloi said...

Puma shoes , Ugg Boots , nike max shoes, NIKE AIR MAX TN ,nike max shoes ,PUMA CHAUSSURES, NIKE SHOX Torch ,puma Ferrari F1 ,PUMA DRIFT CATmens clothing men's sweate, cheap columbia jackets, lacoste sweater, ralph lauren polo shirts,ski clothing. Free Shipping, PayPal Payment. Enjoy your shopping experience on mensclothingstore.Us

Talia.float said...

Bought the Tennis Racquet is important, exercise can reduce the harm, especially for the wrist injury. But the good of Tennis Racket in general in the real prices are more expensive, so a lot of websites now have cheap tennis racquettennis racquet discountcheap tennis racketdiscount Tennis Racket .

Talia.float said...

head junior tennis racketwilson tennis racquet
wilson tennis racket
head tennis racketbabolat tennis racket

ed-hardy-shirts said...

There are ed hardy shirts
,pretty ed hardy shirt for men, ed hardy womens in the ed hardy online store designed by ed hardy ,many cheap ed hardy shirt ,glasses,caps,trouers ed hardy shirts on sale ,
You can go to edhardyshirts.com to have a look ,you may find one of ed hardy clothing fit for you
http://straighthairgirl.blog126.fc2.com
http://www.seriousblogging.com/crazygirlsshirts
http://www.free-blog-site.com/iammyself
http://d.hatena.ne.jp/hotfishing

puma mens shoes
nike air max ltd
NIKE air shoes

nike max ltd
orange converse
adidas shoes
nike shoes
puma shoes
addidas shoes
cheap converse shoes
cheap nike shoes
cheap puma shoes

raul said...

cxvb I like your blog. Thank you. They are really great . Ermunterung ++ .
Some new style Puma Speed is in fashion this year.
chaussure puma is Puma shoes in french . Many Franzose like seach “chaussure sport” by the internet when they need buy the Puma Shoes Or nike max shoes. The information age is really convenient .
By the way ,the nike max ltd is really good NIKE air shoes ,don’t forget buy the puma mens shoes and nike air max ltd by the internet when you need them . Do you know Nike Air Shoes is a best Air Shoes . another kinds of Nike shoes is better . For example , Nike Air Rift is good and Cheap Nike Shoes .the nike shox shoes is fitting to running.
Spring is coming, Do you think this season is not for Ugg Boots? maybe yes .but this season is best time that can buy the cheap ugg boots. Many sellers are selling discounted. Do not miss . Please view my fc2 blog and hair straighteners blog.
.thank you .

I like orange converse shoes ,I like to buy the cheap converse shoes by the internet shop . the puma shoes and the adidas shoes (or addidas shoes) are more on internet shop .i can buy the cheap nike shoes and cheap puma shoes online. It’s really convenient.
Many persons more like Puma basket shoes than nike air rift shoes . the Puma Cat shoes is a kind of Cheap Puma Shoes .
If you want to buy the Cheap Nike Air shoes ,you can buy them online. They are same as the Nike Air shoes authorized shop. Very high-caliber Air shoes and puma cat shoes . the cheap puma shoes as same as other.

haitao said...

cheap hair straighteners
chi hair straightener
chi flat iron

new polo shirts
cheap Lacoste polo shirts
cheap Lacoste polo shirts

cheap handbags
cheap bags
puma chaussures
chaussures puma
chaussure puma

Men's North Face
Women's North Face


hair straighteners
sexy lingerie store
cheap ugg boots
tattoo wholesale
men's clothing
women's clothing


2009 nike shoes
new nike shoes
Women's max
Men's max 93
nike shox
Nike air force
Nike air max 2003
nike air max ltd
nike air max tn
Nike air rift
Nike air Yeezy
nike airmax
Nike air max 90
Nike air max 97
nike birds nest shoes
nike dunk
nike RT1 shoes
nike SB
nike shox shoes
Nike shox OZ shoes
Nike shox R2 shoes
Nike shox R3 shoes
Nike shox R4 shoes
Nike shox R5 shoes
Nike shox TL3
nike trainers lovers

tennis rackets
Wilson tennis rackets
HEAD tennis rackets
Babolat tennis rackets

fdg said...

http://iblog99.edublogs.org/
http://iblog99.blog126.fc2.com/
http://iblog99.blogsome.com/
http://www.soulcast.com/iblog99/

lucyliu said...

nike air max 90
nike air max 95
nike air max tn
nike air rift
nike shox r4
nike air max 360
nike shox nz
puma mens shoes
puma shoes
puma speed
nike shoes
nike air
nike air shoes
puma cat
air max trainers
mens nike air max
nike shoes air max
nike shoes shox
air shoes
nike shoe cart
puma future
cheap puma
sports shoes
nike air rifts
nike air rift trainer
nike air
nike rift
nike rift shoes
cheap nike air rifts
bape shoes
jeans shop
diesel jeans
levis jeans

theprophet said...

sneakers shoes She continued,
"Why...? Don't you need someone to pose as your girlfriend this year?" Then he answered, "No, there is no need for that anymore......"
Before he can continue, he was interrupted, discount nike shoes"Oh yes! Must have found a girlfriend! nike shox r4 You haven't been searching for one for the past years, right?" The man looked up, as if he has struck gold, his face beamed and looked directly at the drunken girl. tn dollarHe replied, "Yes......you are right! I haven't been looking for anyone for the past years."
With that, the man darted across the floor and out the door, cheap nike shoesleaving the lady in much bewilderment. He finally realized that he has already found his dream girl, and she was.....the Vancouver girl all along! The drunken lady has said something that awoken him.
All along he has found his girl.nike tennis shoes That was why he did not bother to look further when he realized she was not coming back. It was not any specific girl he was seeking! cheap nike shoxIt was perfection that he wanted, and yes.....perfection!!
Relationship is something both parties should work on. Realizing that he had let away someone so important in his life, he decided to call her immediately. His whole mind was flooded with fear.free shipping shoes He was afraid that she might have found someone new or no longer had the same feelings anymore..... For once, he felt the fear of losing someone.
As it was Christmas eve, the line was quite hard to get through, especially an overseas call. He tried again and again, never giving up. Finally, he got through......precisely at 1200 midnight. He confessed his love for her and the girl was moved to tears. nike shoes It seemed that she never got over him! Even after so long, she was still waiting for him, never giving up.
He was so excited to meet her and to begin his new chapter of their lives. He decided to fly to Vancouver to join her. It was the happiest time of their lives! nike discount shoes But their happy time was short-lived. Two days before he was supposed to fly to Vancouver,cheap puma shoes he received a call from her father. She had a head-on car collision with a drunken driver. nike shox shoes She passed away after 6 hours in a coma.
The guy was devastated, as it was a complete loss. Why did fate played such cruel games with him? He cursed the heaven for taking her away from him, denying even one last look at her! How cruel he cursed! How he damned the Gods...!!nike free shoes How he hated himself....for taking so long to realize his mistake!! That was in 1996.
The moral of this story is :
Treasure what you have...
Time is too slow for those who wait;
Too swift for those who fear;
Too long for those who grief;
Too short for those who rejoice;
But for those who love...
Time is Eternity.
For all you out there with someone special in your heart, cherish that person, cherish every moment that you spend together that special someone, for in life, anything can happen anytime. buy shoes onlineYou may painfully regret, only to realise that it is too late.