<< October 6, 2009 | Home | October 8, 2009 >>

Wednesday Java Quiz: Think You Understand Concurrency?

There is a war of words going on about simplicity vs. complexity among the pundit circles:

They argue about many things, including test-driven development, architectures, design patterns and threading:

Joel Spolsky: One principle duct tape programmers understand well is that any kind of coding technique that’s even slightly complicated is going to doom your project. Duct tape programmers tend to avoid C++, templates, multiple inheritance, multithreading, COM, CORBA, and a host of other technologies that are all totally reasonable, when you think long and hard about them, but are, honestly, just a little bit too hard for the human brain.
Robert Martin: I found myself annoyed at Joel’s notion that most programmers aren’t smart enough to use templates, design patterns, multi-threading, COM, etc. I don’t think that’s the case. I think that any programmer that’s not smart enough to use tools like that is probably not smart enough to be a programmer period.

While I had my "A-Ha, so this is how TDD works!" moment at a Robert Martin "Scoring Bowling Game" talk, I don't want to argue against Joel either.

Since I'm fixing some long standing bugs (Chris told me "It's been there for years" yesterday) in a piece of software recently, and it has a threading aspect to it, I'll just throw out snippets that I saw while walking through the code, all I ask is:

Q: What's wrong with them? (They are not complete. Use your imagination to fill in the missing parts.)

Snippet 1

public void foo() {
  Object lock = task.getLock();
  synchronized(lock) {
    task.perform();
    lock.wait();
  }
}

Snippet 2

public void run() {
  while (!done) {
    doIt();
    if (done) break;
    try {
      Thread.sleep(60000L);
    } catch (InterruptedException e) {
    }
  }
}

public void stop() {
  done = true;
  while (thread.isAlive()) {
    try {
      Thread.sleep(500);
    } catch (InterruptedException e) {
    }
  }
}

Snippet 3

public void foo() {
  // code
  class Bar {}
  Object lock = new Bar();
  synchronized(lock) {
    // code
    lock.wait();
  }
  // code
  synchronized(lock) {
    // code
    lock.notify();
  }
}