Skip to content

Instantly share code, notes, and snippets.

@tantaman
Last active December 15, 2015 05:59
Show Gist options
  • Save tantaman/5212691 to your computer and use it in GitHub Desktop.
Save tantaman/5212691 to your computer and use it in GitHub Desktop.
3-21-13

If callbacks aren't placed on an event queue, multiple threads begin to share access to someObj.

Object someObj = ...;

Runnable callback = new Runnable(){ someObj.doSomething(); };

executor.submit(new Runnable() {
  public void run() {
    ... do something ...
    // the callback is now run in a different thread
    // than the thread that generated the task!
    // Two different threads now access someObj.
    callback.run();
  }
});

someObj.doSomething();

vs.

Make a simple event queue & task dispatcher class. All callbacks are given to the TaskDispatcher to run. This confines callbacks to a specific thread. Just like what we do in Swing.

TaskDispatcher

// on some custom event dispatch thread
while (true) {
   Task t = queue.take();
   t.run();
}

Object someObj = ...;

Runnable callback = new Runnable() { someObj.doSomething(); };

// submitting a task to run in the background
executor.submit(new Runnable() {
   ... do some intense work ...
  // run the callback back on the dispatch thread
  // only 1 thread ever accesses someObj.
  TaskDispatcher.invokeLater(callback);
});

someObj.doSomething();

Functional?

  • Functions are values
  • Higher order functions (functions that operate on other functions) make the language more "declarative"

Declarative in that you can say what you want, not precisely how to do it.

e.g.:

In English: Multiply all odd numbers from 1 to 100 together.

Or another way: Multiply all odd numbers together in the range from 1 to 101.

Literally: Apply multiplication to all odd numbers in the range from 1 to 101.

In Clojure:

(apply * (filter odd? (range 1 101)))

vs. procedural:

Literally: Start with the number 1. Count from 1 to 101 and multiply each successive odd number by the number you started with OR the result of the previous multiplication, if one exists.

In Java:

int result = 1;
for (int i = 1; i < 101; ++i) {
  if (i % 2 != 0) {
    result = result * i;
  }
}
return result;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment