When Random Food Appears

Isn’t it weird how readily we eat food that randomly appears at work, even though we have no idea who put it there or where it came from? If I found food outside, I wouldn’t eat it. If food randomly appeared in my home, I’d be terrified. But if food appears at the office… sure, I’ll have some without another thought.

The picture below, by the way, is from my three-year work anniversary in January 2014. I brought in 72 donuts. But at least I announced per mailing list that I needed help eating them…

Six dozen donuts for my three-year work anniversary.

Six dozen donuts for my three-year work anniversary.

Share
Posted in Uncategorized | Leave a comment

Print This Post Print This Post  

From Dijkstra to Me in Four Papers

I haven’t written in a while. I at least wanted to write about going snowshoeing while attending an avalanche class. I’ll get to it some day.

Today I found a website that computes distance between computer scientists. Kind of like the Erdős number, but in computer science.

The world is small: I can get from Dijkstra to me in just four papers.

  1. Edsger W. Dijkstra

    worked on 1 publication with
  2. Alan J. Perlis

    worked on 2 publications with
  3. John McCarthy

    worked on 2 publications with
  4. Robert Cartwright

    worked on 3 publications with Mathias Ricken

There are several different ways of getting there:

  1. ALGOL Sub-Committee Report – Extensions.

    Edsger W. Dijkstra and W. Heise and Alan J. Perlis and Klaus Samelson

    Commun. ACM, 1959
  2. Revised report on the algorithm language ALGOL 60. (DOI)

    John W. Backus and Friedrich L. Bauer and Julien Green and C. Katz and John McCarthy and Alan J. Perlis and Heinz Rutishauser and Klaus Samelson and Bernard Vauquois and Joseph Henry Wegstein and Adriaan van Wijngaarden and Michael Woodger and Peter Naur

    Commun. ACM, 1963



    Report on the algorithmic language ALGOL 60. (DOI)

    John W. Backus and Friedrich L. Bauer and Julien Green and C. Katz and John McCarthy and Alan J. Perlis and Heinz Rutishauser and Klaus Samelson and Bernard Vauquois and Joseph Henry Wegstein and Adriaan van Wijngaarden and Michael Woodger

    Commun. ACM, 1960
  3. First Order Programming Logic. (DOI)

    Robert Cartwright and John McCarthy

    Proceedings of the Conference Record of the Sixth Annual ACM Symposium on Principles of Programming Languages, 1979



    Recursive programs as functions in a first order theory. (DOI)

    Robert Cartwright and John McCarthy

    Proceedings of the Mathematical Studies of Information Processing, 1978
  4. DrHJ: a lightweight pedagogic IDE for Habanero Java. (DOI)

    Jarred Payne and Vincent Cavé and Raghavan Raman and Mathias Ricken and Robert Cartwright and Vivek Sarkar

    Proceedings of the 9th International Conference on Principles and Practice of Programming in Java, 2011



    Test-first Java concurrency for the classroom. (DOI)

    Mathias Ricken and Robert Cartwright

    Proceedings of the 41st ACM technical symposium on Computer science education, 2010



    ConcJUnit: unit testing for concurrent programs. (DOI)

    Mathias Ricken and Robert Cartwright

    Proceedings of the 7th International Conference on Principles and Practice of Programming in Java, 2009
Share
Posted in Uncategorized | Leave a comment

Print This Post Print This Post  

More Mt. St. Helens Summit Pictures

Here are some more picture from my trip to summit Mt. St. Helens.

My tent, with Mt. St. Helens in sight.

My tent, with Mt. St. Helens in sight.

I ate some soup and beans, and then hit the sack before 8 PM.

I ate some soup and beans, and then hit the sack before 8 PM.

I broke camp shortly after 5 AM and hit the trail before sunrise.

I broke camp shortly after 5 AM and hit the trail before sunrise.

The first 2 mi were a fast hike through forest, until I reached Monitor Ridge.

The first 2 mi were a fast hike through forest, until I reached Monitor Ridge.

Once the forest cleared, I could see Mt. Hood in the South.

Once the forest cleared, I could see Mt. Hood in the South.

Monitor Ridge looked intimidating.

Monitor Ridge looked intimidating.

Once I was up and over that ridge, I was in the shade. Another advantage of leaving early.

Once I was up and over that ridge, I was in the shade. Another advantage of leaving early.

This is looking down Monitor Ridge to the South.

This is looking down Monitor Ridge to the South.

There wasn't a whole lot of snow left anymore, but some glaciers never melt.

There wasn’t a whole lot of snow left anymore, but some glaciers never melt.

Once I was a bit higher up, I could see Mt. Adams in the East.

Once I was a bit higher up, I could see Mt. Adams in the East.

The snow looked inviting, and at first I considered glissading down, but then I saw this giant crevace.

The snow looked inviting, and at first I considered glissading down, but then I saw this giant crevasse.

It was getting pretty windy, and I had to put my windbreaker on.

It was getting pretty windy, and I had to put my windbreaker on.

After trudging through an eternity of pumice, I reached the peak and the crater rim.

After trudging through an eternity of pumice, I reached the peak and the crater rim.

The view from the peak was glorious.

The view from the peak was glorious.

I could see Mt. Rainier, Mt. Adams, Mt. Hood, Mt. Jefferson farther south in Oregon, and even Mt. Baker 170 miles to the north.

I could see Mt. Rainier, Mt. Adams, Mt. Hood, Mt. Jefferson farther south in Oregon, and even Mt. Baker 170 miles to the north.

When I got to the top, only three other hikers were there. A father and son took my picture.

When I got to the top, only three other hikers were there. A father and son took my picture.

The force it took to blow away half of the mountain is difficult to contemplate.

The force it took to blow away half of the mountain is difficult to contemplate.

The magma dome in the crater is growing. The steam is evidence of active volcanism.

The magma dome in the crater is growing. The steam is evidence of active volcanism.

Over 30 years after the explosion, there are still thousands of trees in Spirit Lake.

Over 30 years after the explosion, there are still thousands of trees in Spirit Lake.

It was a great trip.

It was a great trip.

I may have summit fever. Is Mt. Adams next?

I may have summit fever. Is Mt. Adams next?

On the way down, I saw a chipmunk that wasn't afraid of me at all.

On the way down, I saw a chipmunk that wasn’t afraid of me at all.

Like I already mentioned, it took me about 4 hours up and 3 hours down. I had taken 4 liters of water with me, and I ran out about 20 minutes before I got back to the trailhead. I wish I had had a bit more. I took a few salt tablets with me, and I think that helped me a lot. I didn’t have any issues with cramps.

I had my trekking poles with me, a windbreaker, a fleece, sunglasses, and a hat. I definitely needed all that. What I was almost the most glad about, though, was having taken gloves with me. On the climb down, I often needed to use my hands instead of my trekking poles.

I’m not sure how much more I could do. 7 hours, 10 miles, and 4500 ft climb was quite a bit. But some say you can day-hike Mt. Adams. Or camp at 9000 ft. The roundtrip is 16.0 mi, with 6700 ft elevation gain. Next year…?

Share
Posted in Pictures | 1 Comment

Print This Post Print This Post  

Summited Mt. St. Helens

My wild hair and I summited Mt. St. Helens today. It was a hard hike, but it was worth it.

I climbed about 4500 ft (1,372 m) — that’s over 340 floors in a building! — and hiked 5 miles (8 km) one way up Monitor Ridge, to 8,365 ft (2,550 m) above sea level. And then down again, of course.

At the summit of Mt. St. Helens. That's Mt. Rainier in the background.

At the summit of Mt. St. Helens. That’s Mt. Rainier in the background.

The sky was perfectly clear, and besides Mt. Rainier, I could also see Mt. Hood and Mt. Jefferson in Oregon and even Mt. Baker far in Northern Washington.

Share
Posted in Pictures | 1 Comment

Print This Post Print This Post  

New DrJava stable version: drjava-stable-20130901-r5756

Corky Cartwright, my PhD advisor, released a new version of DrJava today. He writes:

Dear DrJava Users:

We have made a new stable version available: drjava-stable-20130901-r5756

You can download it from the DrJava website at http://drjava.org/
or from SourceForge.net by following this link:

https://sourceforge.net/projects/drjava/files/1.%20DrJava%20Stable%20Releases/drjava-stable-20130901-r5756/

You receive this email because you have subscribed to a DrJava mailing list.


DrJava is a lightweight programming environment for Java designed to foster test-driven software development. It includes an intelligent
program editor, an interactions pane for evaluating program text, a
source level debugger, and a unit testing tool.

In addition to bug fixes, this stable release includes a number of new features introduced after the last stable release:

Note: Java 5 compatibility has been dropped. To use DrJava, you will
need Java 6 or newer.

New features since the last stable release:

  • DrJava is now compatible with Java 8 and perhaps with future editions
    of Java.

Bug fixes since the last stable release:

  • DrJava correctly finds and labels Oracle JDK 7 compilers on Mac OS X.

NOTE: Newer releases of Mac OS X include a gatekeeper that will not run unlicensed applications like DrJava unless you explicitly open DrJava by
“right” (control-key) clicking on the DrJava icon and executing the
“Open” command. After you manually open DrJava once, Mac OS X remembers
that it should be allowed to run and will open DrJava normally like
other applications. Most open source applications like DrJava will not
be licensed on Mac OS X because Apple charges a fee for this service.

I’m still very pleased by how well my auto-update feature in DrJava works.

Share
Posted in DrJava | Leave a comment

Print This Post Print This Post  

Sleep Time

Mostly out of curiosity, I downloaded the Sleep Time app for Android yesterday. It’s an alarm clock that uses the accelerometer in the phone (which has to be placed on the mattress) to determine one’s sleep phase. Based on that information, it wakes you up at a certain point during a 30-minute window, with the goal of not tearing you out of deep or REM sleep.

I set the alarm clock to 7 AM, but the app actually woke me up at 6:34 AM. Judging by the sleep cycle graph, that was probably the right call, I had been in light sleep for a while.

My sleep cycle graph is so pretty! Apparently I’m quite a normal sleeper.

Sleep Cycle Graph 2013-07-11

Sleep Cycle Graph 2013-07-11

Update:

OMG. When talking to guys at work, I realized what an evil genius would do with an app like this: Market the sleep cycle information to advertisers (or worse!), who will then play audio messages to the sleepers! Am I being brainwashed?

Share
Posted in Uncategorized | Leave a comment

Print This Post Print This Post  

New Phone: Samsung Galaxy S4

In January 2011, I switched from my old Pam Treo 755p to an Android touch screen smartphone. At first I was skeptical about not having a keyboard, but boy, that was the right decision. I’d had the HTC EVO 4G on Sprint for about two years and three months, and it was a really solid phone. Memory was getting a little tight, with apps like Amazon Kindle taking over 20 MB, but it was still good. I also had the best car dock ever, the Seidio Innotraveler: I just had to slip the phone into the dock, and it connected. No cords, just one hand.

But the USB connector was starting to become unreliable, and since Sprint does not reduce the bill after the 24 month minimum contract length was over, I was essentially subsidizing Sprint now. It was time for a new phone. I also looked at cell phone coverage maps and download speeds, and Sprint really wasn’t doing so well. A co-worker recommended T-Mobile (yeah… I’m back under the descendent of the Deutsche Bundespost, the former German post and phone monopoly holder), and I like the fact that the payments go down after 24 months. That actually makes sense.

So I switched from Sprint to T-Mobile and got a Samsung Galaxy S4. Well, actually, from Sprint to i-Wireless with my spare dumbphone to T-Mobile, because Sprint deactivated my line immediately, and it took a week to get the new phone from T-Mobile.

I like the new phone. It has a bigger screen, which is something I didn’t actually want, but it’s thinner and lighter, so it actually feels like I’m carrying around less. And it’s a lot faster. T-Mobile also is a lot faster than Sprint. I like the fact that I can make free calls when I’m on a WiFi network. When I’m traveling internationally, I can call the US for free (provided I have wireless internet)!

Google Now, which I didn’t know about before but which came pre-installed on the Galaxy S4, is pretty cool. It does a pretty good job of displaying what I actually want to know. And Google Currents has become my favorite way of reading… stuff. I don’t have all my feeds in there, those are in feedly now with the looming shutdown of Google Reader, but I have to admit, I probably have too many feeds anyway. I can’t keep up.

Some of the gadgets of the Galaxy S4 are cool, but I don’t use them too much. I like Multi-window, but I’d like more multi-window enabled applications for simpler multitasking. Smart Stay, the phone’s ability to stay on while I’m looking at it, or pausing a video when I look away, can be useful. But some of the other stuff, like waving my hand over the phone, I don’t really use.

The camera on the Galaxy S4 has a lot of bells and whistles too, like an easy to use panorama mode, but I don’t use most of them. At least, I haven’t yet. Eraser, Drama, and Best Face all sound good, but I haven’t found applications for them yet. And over all, I think the Galaxy S4’s camera is worse than that of the EVO 4G, especially under low-light conditions. With the EVO 4G, I rarely had to use the flash, now photos often are too dark without it. And to make matters worse, I think the flash is worse too on the Galaxy S4.

The Galaxy S4 itself is slim and light, but the phone feels plasticy and cheap. I always get a case, though, and I chose the same case that I had on my old phone, a Seidio Surface. And guess what, this case is available with a kickstand, a convenient feature of my old phone. Now, with the Seidio Surface case, the Galaxy S4 feels solid again.

I got an iBOLT xProDock active car dock for my car, and while it works, it’s not nearly as nice as the old Innotraveler. It takes two hands to get the phone in or out, because I have to lift a little clamp and plug in a little cord.

Oh Seidio, won’t you make an Innotraveler for the Galaxy S4, please?

Another neat thing about T-Mobile and the Galaxy S4 is that it uses a SIM card. That means when I travel, I can put another SIM card in, like the Vodafone SIM card that I’ve been using when I’m in Europe. Unfortunately I haven’t got to try this out yet because when I was traveling in May, I didn’t have a SIM card cutter yet, and my Vodafone SIM card was a full-size card, but the Galaxy S4 needs a mini-SD card.

I’m paying a bit more, $94 a month instead of about $60 to $64. But I have to admit, the Sprint Employee Referral Offer plan was a fricking steal! Right now, I’m pretty happy with my decision. I just home this phone also lasts two years.

Old phone (left): HTC EVO 4G. New phone (right): Samsung Galaxy S4.

Old phone (left): HTC EVO 4G. New phone (right): Samsung Galaxy S4.

New phone, Samsung Galaxy S4, feels cheap without case. The Seidio Surface case remedies that well.

New phone, Samsung Galaxy S4, feels cheap without case. The Seidio Surface case remedies that well.

New phone, Samsung Galaxy S4, feels cheap without case. The Seidio Surface case remedies that well.

New phone, Samsung Galaxy S4, feels cheap without case. The Seidio Surface case remedies that well.

PS: I faced a small conundrum when I was taking that first picture of the new and the old phone: How would I take the picture? I take most photos with my phone, and I’ve been doing that for a couple of years now. Of course, I took out my Canon G12, a great camera that I don’t use often enough…

Share
Posted in Uncategorized | 1 Comment

Print This Post Print This Post  

Healthiest On-Call Week

At work, every engineer has a pager. Every few weeks, depending on the team, an engineer is on-call and needs to respond quickly in case something breaks in the team’s products.

The week ending today was, fortunately, very quiet. There were only a few events, and none of them were at night. Additionally, I think this was the healthiest on-call week I’ve had so far.

In the past, I didn’t exercise at all when on-call. It feels like I can’t run or bike as easily, because I have to carry my backpack everywhere. I definitely can’t go hiking, because I need to stay within cell phone range. And (maybe that’s just me) I was worried about not hearing the pager if I left it by the pool side at the gym.

A while ago, I remembered that my office building had a gym. This week, I decided to go to that gym and use the exercise bikes and elliptical machines there. If my pager went off… no problem, I’d just head up to my office, where I had left my laptop. In fact, I had my desktop there too, so I’d even be in a better position to work than if I were at home.

And it felt great. I went to that gym on six days, for an hour each. I think I’ll continue to do that, at least for this next week, when I’m secondary and still need to wear my pager and take my backpack everywhere.

I’ve also started to like the elliptical machines. I started running again a few weeks ago, after not having run since… last July? I was happily surprised that I could still easily run over 4 miles. Unfortunately, I might have ramped up my distance and speed too quickly, and my right knee got inflamed. The elliptical gives me a similar feeling as running, but with much less impact.

Share
Posted in Uncategorized | Leave a comment

Print This Post Print This Post  

A Professor’s Prayer

From PhD Comics:

PhD Comics: A Professor's Prayer

A Professor’s Prayer

Share
Posted in Uncategorized | Leave a comment

Print This Post Print This Post  

Snorkeling Pictures

I finally got the snorkeling pictures from last month developed. I think they call it “developing” — it’s been a while since I’ve used real film.

Share
Posted in Pictures | Leave a comment

Print This Post Print This Post  

Pictures from Recent Journeys

I’ve done a fair amount of traveling again recently. It was exciting, and I got some much needed sun in the last two trips, but it’s good to be home again. For a while.

The most wonderful heated outdoor saltwater pool in Vancouver.

The most wonderful heated outdoor saltwater pool in Vancouver.

Poipu beach.

Poipu beach.

Hiking on Kauai: Na Pali coast.

Hiking on Kauai: Na Pali coast.

Hiking on Kauai: Na Pali coast.

Hiking on Kauai: Na Pali coast.

Hiking on Kauai: Na Pali coast. The view, or lack thereof, an hour later.

Hiking on Kauai: Na Pali coast. The view, or lack thereof, an hour later.

Wailua beach.

Wailua beach.

My friend, Mt. Rainier. From 38,000 ft.

My friend, Mt. Rainier. From 38,000 ft.

Grand Canyon, on the way to Arizona.

Grand Canyon, on the way to Arizona.

Share
Posted in Pictures | Leave a comment

Print This Post Print This Post  

Java Executors, Continuations, and Small Step Semantics

In my book club at work, we’re discussing the book Java Concurrency in Practice by Brian Goetz et al. This Tuesday, we talked about Chapter 8, Applying Thread Pools, and in particular about how to correctly size thread pools.

Listing 8.1 in the book points out what the authors call “thread starvation deadlock.”

[cc_java]
public class ThreadDeadlock {
ExecutorService exec = Executors.newSingleThreadExecutor();

public class RenderPageTask implements Callable {
public String call() throws Exception {
Future header, footer;
header = exec.submit(new LoadFileTask(“header.html”));
footer = exec.submit(new LoadFileTask(“footer.html”));
String page = renderBody();
return header.get() + page + footer.get(); // will deadlock — task waiting for result of subtask
}
}
}
[/cc_java]

This is the same situation that we’ve often encountered, and that I have written about in papers and my theses, namely calling [cc_java inline=”true”]SwingUtilities.invokeAndWait(Runnable r)[/cc_java] from within the event dispatch thread. The task A currently running in a thread is waiting for another task B to finish running in that thread, but task B can never even start because A is still running.

Here, of course, the problem is made deterministically repeatable because there is only one thread. The above code is guaranteed to deadlock. It is noteworthy that this kind of thread starvation deadlock can happen with multiple threads as well. Let’s say, for example, that our executor has 10 threads running. It is possible that all 10 of the threads run tasks that get to a point where they schedule a subtask and wait for that task’s completion. These tasks cannot be executed right away, so they go into a queue — and that’s where they will sit forever, at least if the queue can accommodate at least 10 subtasks. If submitting one of those tasks get rejected, then it is possible that the parent task fails and frees up a thread, but that’s still not certain.

After going back and forth in trying to either prevent bad things from happening, or at least detecting when they do, we came to the conclusion that submitting subtasks to the same executor from which the current thread originated is generally a bad idea.

The right thing to do is to schedule subtasks and return. The parent task should never wait for the subtasks. If you need to perform some kind of processing on the finished subtasks, you can use Guava’s [cc_java inline=”true”]ListenableFuture[/cc_java] to register a listener or callback that gets executed when the future finishes.

[cc_java]
public class ThreadDeadlock {
ListenableExecutorService exec =
MoreExecutors.listeningDecorator(
Executors.newSingleThreadExecutor());

public class RenderPageTask implements Runnable {
public void run() {
final ListenableFuture header, footer;
header = exec.submit(new LoadFileTask(“header.html”));
footer = exec.submit(new LoadFileTask(“footer.html”));
final String page = renderBody();
header.addListener(new Runnable() {
public void run() {
footer.addListener(new Runnable() {
public void run() {
String result = header.get() + page + footer.get();
// now how do we get this result out?
}
}, exec);
}
}, exec);
}
}
}
[/cc_java]

What I thought was interesting here was that we were using continuations here. This may have been obvious to everyone else, but it had never occurred to me that the right way of using Java executors was by modeling continuations. Then my programming languages background kicked in, and I noticed that we were using a small-step semantics here. I’ve always felt that big-step is conceptually simpler to understand, but that small-step has so many advantages. Better, safer concurrency in Java is one I hadn’t considered.

Share
Posted in Uncategorized | Leave a comment

Print This Post Print This Post  

Practice Pays Off!

I reviewed the video recording of my first company-wide internal talk, which I gave twice together with one of my colleagues on October 23 and 25. Practice really pays off!

October 25, 2012

October 25, 2012

I’ve never practiced this much for any talk, not even for any of my thesis defenses, and I think it really shows. We had two coaching sessions, two coaches, and did three full dry-runs. I’m impressed by the aid that my company gives to its speakers. Thank you.

Share
Posted in Pictures | Leave a comment

Print This Post Print This Post  

XPS 8300 Shortcomings

So, now that I have disposed of my old Dimension 9200, I realize that the new (well, year-old?) XPS 8300 isn’t really all that expandable. The Dimension 9200 absolutely crushed it in that category.

In the Dimension 9200, I could fit two optical drives and four hard drives, and guess what, there actually were internal SATA ports for all six of them. It also had one PCI Express x16 slot, one PCI Express x4 slot, one PCI Express x1 slot, and three PCI slots.

Dell Dimension 9200 board

Dell Dimension 9200 board

The XPS 8300 only has space for two hard drives and two optical drives. I suppose I could get rid of the rather useless 3.5″ drive bay insert with one USB 3.0 connector (really? one?!) in it and replace it with another hard drive, but then I’d have to buy another SATA controller. Because the XPS 8300 only has four SATA ports. And in addition to the one PCI Express x16 slot for the graphics card, there are only three PCI Express x1 slots.

Dell XPS 8300 board

Dell XPS 8300 board

Now I have two SATA hard drives from my old computer sitting around (500 GB + 160 GB) and nothing to do with them. I also kind of want a graphics card that has two DVI connectors. Then I could more easily hook up my work laptop.

For my next computer, will I try to get a bigger, more extensible case again? I don’t know. I’ve been trying to downsize…

Share
Posted in Ramblings | Leave a comment

Print This Post Print This Post  

RIP, Dell Dimension 9200

My old Dell Dimension 9200 computer broke yesterday. I took a look at it today and couldn’t figure out what the problem was. Just diagnostic lights 1, 2, and 3 lit, which according to Dell’s Users Guide means “other failure.” I checked all hard drive and power connectors, re-seated all RAM modules and extension cards, to no avail.

I had thought before that maybe I have too many computers in the house, definitely more than I need. I don’t do as much with my computers at home anymore, so I didn’t put as much energy into fixing the Dimension 9200 as I would have in the past.

Still, this was a good computer. I bought it in January 2007, and with its 2.4 GHz Core 2 Duo CPU, 2 GB of RAM (later 4 GB), and 7200 RPM SATA hard drive, it greatly sped up a lot of my research work in grad school. It had a great, simple, and expandable case.

I do have to admit, though, that a few years ago, the power supply gave out, and I had to replace it. The computer that it replaced was rather short-lived, from mid-2005 to January 2007. The computer before that, a Pentium III 733 MHz from Micron, lasted me from the beginnings of undergrad in August 2000 until I moved to Seattle in 2011 (although it wasn’t my primary machine anymore after mid-2005).

I’ll miss the Dimension 9200.

Share
Posted in Uncategorized | 1 Comment

Print This Post Print This Post  

Problems with RejectedExecutionHandler and Futures

I’ve been working with [cc_java inline=”true”]ThreadPoolExecutor[/cc_java] and [cc_java inline=”true”]RejectedExecutionHandler[/cc_java]. The executor framework provides a convenient way to distribute concurrent tasks to multiple threads, and the different [cc_java inline=”true”]RejectedExecutionHandler[/cc_java] policies, [cc_java inline=”true”]ThreadPoolExecutor.DiscardOldestPolicy[/cc_java], for instance, enable your program to shed load if there is more work than it can reliably handle.

Unfortunately, when I started using [cc_java inline=”true”]Future[/cc_java]s, things became complicated. Consider the following example:

[cc_java]
ThreadPoolExecutor es = new ThreadPoolExecutor(10, 10, 1, TimeUnit.MINUTES, new ArrayBlockingQueue(10),
new ThreadPoolExecutor.DiscardOldestPolicy());

List> futures = Lists.newArrayList();
for(int i=0; i<30; ++i) { final int ii = i; futures.add(es.submit(new Callable() {
public Integer call() {
System.out.println(“Running task ” + ii);
try {
Thread.sleep(1000);
} catch(InterruptedException e) {
// ignore
}
System.out.println(“Task ” + ii + ” ends”);
return ii;
}
}));
}

for(Future f: futures);
System.out.println(“Result: ” + f.get());
}
[/cc_java]

It creates a thread pool with a maximum of 10 threads, and a work queue that can hold another 10 items. The policy to shed load is [cc_java inline=”true”]ThreadPoolExecutor.DiscardOldestPolicy[/cc_java], which means it will favor newer tasks over older tasks, if the queue has reached its capacity.

Then the program creates 30 tasks and submits them to the executor service. The tasks each sleep for a second to make sure we actually hit the capacity of the thread pool executor. As a result, only 20 can be submitted (10 running, but sleeping, and another 10 in the work queue), and 10 need to be rejected. The tasks that are rejected are actually the ones that were in the queue first (the older tasks), so we can expect tasks 0 to 9 as well as 20 to 29 to execute.

There is a problem, however, when we wait for the results of tasks 10 to 19 by calling their [cc_java inline=”true”]Future.get()[/cc_java] methods: Because the tasks have been rejected, they never start running, which means they will never finish. The program hangs here.

The only [cc_java inline=”true”]RejectedExecutionHandler[/cc_java]s in the JDK that function correctly here are [cc_java inline=”true”]ThreadPoolExecutor.AbortPolicy[/cc_java] and [cc_java inline=”true”]ThreadPoolExecutor.CallerRunsPolicy[/cc_java]. [cc_java inline=”true”]ThreadPoolExecutor.AbortPolicy[/cc_java] throws a [cc_java inline=”true”]RejectedExecutionException[/cc_java] at the time the task is submitted to the executor service already, not later, and therefore does not return a [cc_java inline=”true”]Future[/cc_java] to wait for. [cc_java inline=”true”]ThreadPoolExecutor.CallerRunsPolicy[/cc_java] executes the task at the time it is executed at the time it is added to the executor service, and while it returns a [cc_java inline=”true”]Future[/cc_java], that [cc_java inline=”true”]Future[/cc_java] is done immediately, and therefore, getting the [cc_java inline=”true”]Future[/cc_java]’s result later will not block.

But what’s the right thing to do here for [cc_java inline=”true”]ThreadPoolExecutor.DiscardPolicy[/cc_java] and [cc_java inline=”true”]ThreadPoolExecutor.DiscardOldestPolicy[/cc_java]? Submitting tasks with these policies does return a [cc_java inline=”true”]Future[/cc_java], but if the task is rejected, that [cc_java inline=”true”]Future[/cc_java] will never be done.

I haven’t found a good solution with the built-in classes of the JDK yet. What I have done now is to cancel the [cc_java inline=”true”]Future[/cc_java] in the [cc_java inline=”true”]RejectedExecutionHandler[/cc_java]. Unfortunately, that can’t easily be done with the existing [cc_java inline=”true”]RejectedExecutionHandler[/cc_java] policies, like [cc_java inline=”true”]ThreadPoolExecutor.DiscardOldestPolicy[/cc_java].

[cc_java]
public class DiscardAndCancelOldestPolicy implements RejectedExecutionHandler {
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
if (!e.isShutdown()) {
Runnable rejected = e.getQueue().poll();
if (rejected instanceof Future) {
((Future) rejected).cancel(false);
}
e.execute(r);
}
}
}
[/cc_java]

[cc_java]
public class DiscardAndCancelPolicy implements RejectedExecutionHandler {
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
if (r instanceof Future) {
((Future) r).cancel(false);
}
}
}
[/cc_java]

Now we can use those policies, and the program behaves as expected. For example:

[cc_java]
ThreadPoolExecutor es = new ThreadPoolExecutor(10, 10, 1, TimeUnit.MINUTES, new ArrayBlockingQueue(10),
new DiscardAndCancelOldestPolicy());

List> futures = Lists.newArrayList();
for(int i=0; i<30; ++i) { final int ii = i; futures.add(es.submit(new Callable() {
public Integer call() {
System.out.println(“Running task ” + ii);
try {
Thread.sleep(1000);
} catch(InterruptedException e) {
// ignore
}
System.out.println(“Task ” + ii + ” ends”);
return ii;
}
}));
}

for(Future f: futures);
try {
System.out.println(“Result: ” + f.get());
} catch(CancellationException e) {
System.out.println(“Task was cancelled”);
}
}
[/cc_java]

Note that now you have to catch the [cc_java inline=”true”]CancellationException[/cc_java] when getting the [cc_java inline=”true”]Future[/cc_java]’s result, because discarding the task will cancel the [cc_java inline=”true”]Future[/cc_java].

Guava’s [cc_java inline=”true”]Futures.successfulAsList[/cc_java] method makes things a bit easier if what you want to do is wait for all [cc_java inline=”true”]Future[/cc_java]s to finish, and then look at the results. It returns [cc_java inline=”true”]null[/cc_java] for failed or cancelled tasks, including the ones our policies reject:

[cc_java]
ThreadPoolExecutor tpe = new ThreadPoolExecutor(10, 10, 1, TimeUnit.MINUTES, new ArrayBlockingQueue(10),
new DiscardAndCancelOldestPolicy());
ListeningExecutorService es = MoreExecutors.listeningDecorator(tpe);

// …

Future> all = Futures.successfulAsList(futures);
List results = all.get();
[/cc_java]

Got something better?

Share
Posted in Uncategorized | Leave a comment

Print This Post Print This Post  

Rice University Centennial Celebration

A lot of good things turn 100 this year, apparently. After attending the ACM Turing Centenary Celebration, I attended the 100th homecoming of my alma mater, Rice University.

It was a great time to return, as many of my friends had come back too. And the Centennial Spectacle, an audio-visual presentation projected onto the buildings in the Academic Quad, was quite something. I had goosebumps for most of the 15 minutes that it lasted.

Share
Posted in Pictures, Uncategorized | Leave a comment

Print This Post Print This Post  

More Hiking Experiences

I can’t write specifics about what I do at work, and lately in my free time, hiking is what I’ve been doing. At the risk of turning this into a hiking blog, here are some details about another hike I did.

I drove to the Rainy Pass on the North Cascades Highway to do the Heather Pass-Maple Pass loop. It was my longest drive to go hiking yet, a little over three hours.

The hike started out rather easy (going counter-clockwise towards Heather Pass), definitely compared to last weekend, going from White River up to Sunrise at Mt. Rainier.

At Heather Pass, I saw smoke rising from near Lewis Lake, and then a tree burst into flames:

A little bit later, a helicopter showed up, left again, and then started shuttling water to the fire. I felt adventurous, deviated from my planned route, and climbed up to Horseshoe Pass so I could see the fire again. It wasn’t a large wildfire, but a wildfire nonetheless.

I was never in danger, of course, other than the dangers that are inherent in hiking. On my way down, I met a woman who had just broken her leg. She was sitting at the side of the trail with a friend, waiting for help. Two other friends had rushed down to the trailhead to get medics. Of course, no phones work within about an hour’s drive. I asked if she needed anything, water or food, but she said she was fine.

I was worried, because it would get dark and cold soon. The night before, it was freezing. It took me about an hour to get down to the trailhead from there, and when I got there, firefighters had already arrived. I gave them my map and showed them where the woman was.

The firefighters said they’d have until about 7:30 PM to get her down, after that it would be too dangerous for everyone. They were readying a helicopter. Someone with EMT experience said a helicopter rescue costs $30,000 just for transportation.

I hope everything worked out for her.

Share
Posted in Pictures | Leave a comment

Print This Post Print This Post  

Three New Hiking Experiences

I’ve kept up my goal this month to go hiking every weekend. Among other places, I went to Marmot Pass, my first trip to the Olympic Peninsula; and a third trip to Mount Rainier this year, this time to Sunrise.

There were a few new experiences.

Hiking in the rain.

Hiking in the rain.

Hiking in the cold.

Hiking in the cold.

Hiking around a bear.

Hiking around a bear.

This wasn’t my first bear on a hike, but I’ve never been this close. I think we almost surprised each other, which can have disastrous consequences. I’m hiking alone, and that means I’m not talking, like many other groups.

The bear was on the trail from the White River Campground north to the path between Sunrise and Shadow Lake. It was next to the trail, right where the trail makes a sharp turn to the right. I noticed the bear first, I think, and kind of
said “holy shit”, because the bear was maybe 30 feet away. Then the bear noticed me and grunted, and ran
north. The bear stopped on the next part of the trail, and
that was the problem: When I came
around the corner, I had to get the bear to move off the path again.
So I just talked and coughed and made some noise, while slowly moving
closer. After maybe a minute, the bear got annoyed and ran south
again, to where I had seen it first.

The bear didn’t look too big, perhaps the size of a human crouching
down on all fours. When I think bears, I think grizzlies, I guess. But
that bear definitely had four-paw drive–it was so fast!

Share
Posted in Pictures | Leave a comment

Print This Post Print This Post  

So You Know What I Did This Summer

Loving the Northwest and my job.

  • Three kayaking trips
  • Two whitewater rafting trips
  • Four days of hiking at Mt. Rainier
  • Solo hiking day trip into the Cascades
  • Business trip to Ireland and Romania

I was too busy in Ireland to take pictures. My co-workers there were great, though, as were the Romanians. Romania was more polarizing: There were a lot of parts of Iasi, the city, that still looked like they were from the communist era (because they were), and other parts that looked brand spanking new. The office there offered a lot more personal space than our Seattle offices.

Share
Posted in Pictures | Leave a comment

Print This Post Print This Post