My dreams of a Nexus One came to naught. But...
I now have an excellent Samsung Galaxy S with Android 2.1, and I asked JetBrains for an open-source license for their Android plugin to IntelliJ IDEA. I have plans brewing!
My dreams of a Nexus One came to naught. But...
I now have an excellent Samsung Galaxy S with Android 2.1, and I asked JetBrains for an open-source license for their Android plugin to IntelliJ IDEA. I have plans brewing!
I'm speaking at Houston TechFest on October 9! My talk is Hands-free Coding: Code Generation with Annotation Processors. Wish me luck. Here's the summary:
Have you ever written hundreds or thousands of lines of boilerplate code, or struggled to write Java idioms correctly every time? There is great way to save time and effort and use to standard code patterns automatically: Code Generation.
In this talk, I will walk you through using the JDK6 Annotation Processor API together with Velocity templates to read your Java source code and write new Java source files for you from code templates. It is magic, but magic you can understand and use to be more productive.
Let the compiler write your code for you!
Please come watch!
With Lua coming to LOTRO I may have to dust off my Lua, last used in hacking at T.o.M.E.. It will be a nice break from Java and work, and give me something nice to do for my wife who doesn't know (yet) about MMORPG add-ons.
Courtesy of Naresh Jain comes J B Rainsberge's list of 10 things to stop doing or he will bury you alive in a box (about 1hr30m of video), a really delightful presentation on agile.
For the impatient, the list (which is only about half the presentation):
Go watch the whole thing, and please, Stop It.
James Gosling tells a great tale on why Sun failed. Spoiler: the alpha particles did it.
Mindshare is a term I rarely hear outside of business or technology magazines, but is very appropriate here. Java has long been king in the unit testing space, and though hoary, JUnit is still one of the best unit testing libraries around.
But Ruby is giving Java serious competition. I am late to the party, but just ran across metric_fu in this post. I wish I had metric_fu for Java!
In the 90s the evolving Java ecosystem was the top reason I moved from C/C++ to Java. JDK7 looks to keep Java the language on life support so it will not immediate wither away (although who came up with the name public defender methods [PDF]?). But the library momentum is not in Java's favor at the moment.
Paul Holser, a fellow ThoughtWorks alum, wrote a nice library for handling properties, property-binder. More to the point, it is an example of PICA style (proxied interfaces configured with annotations), something Paul wrote about recently.
property-binder works using dynamic proxies to turn one kind of call (a typed API) into another (lookups of properties). This is elegantly done.
An alternative for situations where proxies are not appropriate is to use the code-generation facility of annotations, to write Java code for the conversion. The user of annotations cannot tell the difference: the same annotations, interfaces and static factory methods appear in both cases.
This is an interesting corner of Java, bringing together several advanced features but leaving them accessible to the caller with elementary techniques.
I need to track changing data in Java. For example, say I am collecting data sets of some real world behavior, and I'd like to know what has changed between individual readings: additions, removals, changes.
I start with a single datum:
public static class Example {
public final int index; // primary key
public final double value; // satelite data
public final long access; // other data
public Example(final int index, final double value,
final long access) {
this.index = index;
this.value = value;
this.access = access;
}
@Override
public boolean equals(final Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
final Example example = (Example) o;
if (index != example.index)
return false;
return true;
}
@Override
public int hashCode() {
return index;
}
} Reducing to essentials:
Example instances with the same index represent the same "thing"Now equals and hashCode take care of matching equivalent data so I can compare values between data sets. But I also need to know if the satellite data has changed:
public static class ExampleComparator
implements Comparator<Example> {
@Override
public int compare(final Example a, final Example b) {
final int c = Integer.valueOf(a.index).compareTo(b.index);
if (0 != c)
return c;
return Double.valueOf(a.value).compareTo(b.value);
}
} An important point to consider: why not have Example implement Comparable<Example> instead of the separate comparator class? Read the Comparator javadocs closely: you really want equals and compareTo to agree (the discussion is good — I have a new source of bugs to comb out of my code base).
But here equals looks at only primary keys and the comparator looks at both primary keys and satellite data: they do not agree.
Having all the tools I need, time for comparing data sets (please be kind about the weak class name):
public class Differator<T, C extends Comparator<T>> {
private final Map<T, T> items = new HashMap<T, T>();
private final C comparator;
public static <T, C extends Comparator<T>> Differator<T, C> newDifferator(
final C comparator) {
return new Differator<T, C>(comparator);
}
public Differator(final C comparator) {
this.comparator = comparator;
}
public Changes<T> replaceAll(final Set<T> newItems) {
final Changes<T> changes = new Changes<T>();
for (final T item : items.keySet())
if (!newItems.contains(item)) {
changes.deleted.add(item);
items.remove(item);
}
for (final T newItem : newItems) {
if (!items.containsKey(newItem))
changes.inserted.add(newItem);
else {
final T item = items.get(newItem);
if (0 != comparator.compare(item, newItem))
changes.updated.add(new Delta<T>(item, newItem));
}
items.put(newItem, newItem);
}
return changes;
}
public static class Delta<T> {
public final T item;
public final T newItem;
public Delta(final T item, final T newItem) {
this.item = item;
this.newItem = newItem;
}
@Override
public boolean equals(final Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
final Delta delta = (Delta) o;
if (!item.equals(delta.item))
return false;
if (!newItem.equals(delta.newItem))
return false;
return true;
}
@Override
public int hashCode() {
int result = item.hashCode();
result = 31 * result + newItem.hashCode();
return result;
}
}
public static class Changes<T> {
public final Set<T> inserted = new HashSet<T>();
public final Set<Delta<T>> updated = new HashSet<Delta<T>>();
public final Set<T> deleted = new HashSet<T>();
@Override
public boolean equals(final Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
final Changes changes = (Changes) o;
if (!deleted.equals(changes.deleted))
return false;
if (!inserted.equals(changes.inserted))
return false;
if (!updated.equals(changes.updated))
return false;
return true;
}
@Override
public int hashCode() {
int result = inserted.hashCode();
result = 31 * result + updated.hashCode();
result = 31 * result + deleted.hashCode();
return result;
}
}
} It was not much effort to write Differator. replaceAll swaps out a new data set for an old one, returning how they two differed. Credit for immediately spotting that Differator is not merely thread unsafe, it is very unsafe. But this is not hard to address in a simple way.
Lastly, some tests:
public class DifferatorTest {
private Differator<Example, ExampleComparator> differator;
private Example item;
private Changes<Example> changes;
@Before
public void setUp()
throws Exception {
differator = newDifferator(new ExampleComparator());
item = new Example(1, 3.14159, 123);
changes = differator.replaceAll(singleton(item));
}
@Test
public void testFirstInsert() {
assertThat(changes.inserted, is(equalTo(singleton(item))));
assertThat(changes.updated.isEmpty(), is(true));
assertThat(changes.deleted.isEmpty(), is(true));
}
@Test
public void testUpdateUnimportantData() {
final Changes<Example> changes = differator
.replaceAll(singleton(new Example(1, 3.14159, 456)));
assertThat(changes.inserted.isEmpty(), is(true));
assertThat(changes.updated.isEmpty(), is(true));
assertThat(changes.deleted.isEmpty(), is(true));
}
@Test
public void testUpdateSatelliteData() {
final Example newItem = new Example(1, 2.71828, 123);
final Changes<Example> changes = differator
.replaceAll(singleton(newItem));
assertThat(changes.inserted.isEmpty(), is(true));
assertThat(changes.updated, is(equalTo(
singleton(new Differator.Delta<Example>(item, newItem)))));
assertThat(changes.deleted.isEmpty(), is(true));
}
@Test
public void testUpdatePrimaryKey() {
final Example newItem = new Example(2, 3.14159, 123);
final Changes<Example> changes = differator
.replaceAll(singleton(newItem));
assertThat(changes.inserted, is(singleton(newItem)));
assertThat(changes.updated.isEmpty(), is(true));
assertThat(changes.deleted, is(singleton(item)));
}
}
Alex Blewitt writing on InfoQ posts an excellent write up on the state of lambda in JDK7.
It is exciting to see Oracle move on this front publicly after long months invisibility. Two interesting potential features I am rooting for: SAMs and this for recursion.
CallerData.isDirectlyInvokingClass(String, String). It tells logback if a given stack frame is internal to logback or from the calling application. It is static and logback has no hooks for changing its behavior. What to do?public class Wrapper {
static {
new MockUp() {
CallerData it;
@Mock(reentrant = true)
public boolean isDirectlyInvokingClass(
final String currentClass,
final String fqnOfInvokingClass) {
return it.isDirectlyInvokingClass(
currentClass, fqnOfInvokingClass)
|| currentClass.equals(Wrapper.class.getName());
}
};
}
// Rest of class
}
Enter the clever jmockit library sitting at the high end of the testing mock library pile up (or deep end, if you prefer). Jmockit is not the easiest library to use, but is has more code-fu per line than most other swiss-army knives.Through the magic of ServiceLoader you can automate the wiring of your classpath components:
public static void main(final String... args) {
final Injector injector = Guice.createInjector(
ServiceLoader.load(Module.class).iterator());
// Use injector here, etc.
} For each jar or classpath component, include a META-INF/services/com.google.inject.Module file containing the class name of a Guice module which can configure the jar, e.g., hm.binkley.rice.MobModule.
This makes your jars auto-configuring. Merely including them in the classpath is sufficient to be injected into your application. You will find multibindings useful for each jar to provide a well-known list of services without them colliding.
This compiles:
public static void main(final String... args) {
final Fred fred = new Fred();
final Integer i = fred.get(Integer.class);
}
public interface Bob {
<T> T get(final Class<T> type);
}
public static class Fred implements Bob {
@Override
public <T> T get(final Class<T> type) {
return type.cast(null);
}
} This does not:
public static void main(final String... args) {
final Fred fred = new Fred();
final Integer i = fred.get(Integer.class);
}
public interface Bob {
<T> T get(final Class<T> type);
}
public static class Fred<Q> implements Bob {
@Override
public <T> T get(final Class<T> type) {
return type.cast(null);
}
} But this does:
public static void main(final String... args) {
final Fred<?> fred = new Fred();
final Integer i = fred.get(Integer.class);
}
public interface Bob {
<T> T get(final Class<T> type);
}
public static class Fred<Q> implements Bob {
@Override
public <T> T get(final Class<T> type) {
return type.cast(null);
}
} And this does:
public static void main(final String... args) {
final Fred fred = new Fred();
final Integer i = ((Bob) fred).get(Integer.class);
}
public interface Bob {
<T> T get(final Class<T> type);
}
public static class Fred<Q> implements Bob {
@Override
public <T> T get(final Class<T> type) {
return type.cast(null);
}
} What is going on here?
UPDATE: Thanks to Bob Lee in the comments, I see what is going on. Using a class-level raw type results in the methods of that class also being treated as raw types, even though the type parameters of the class and method are separate. (NB — this does not apply to static methods, only instance methods.)
Fritz Thomas solves a common shell scripting problem for me: finding where your script lives. This script saved as ~/bin/x:
#!/bin/bash echo "$0" readlink -f "$0"
With ~/bin in PATH produces:
$ cd ~/bin; ./x ./x /home/where/the/heart/is/bin/x $ cd; x /home/where/the/heart/is/bin/x /home/where/the/heart/is/bin/x
Just what I need! (Yes, quite an odd home directory.)
Do note the caveats for readlink(1).
JPMorgan is hiring in Houston for experienced core Java hands. Please drop me a line if you are interested.
I'm timing code on Windows and I notice calls take either 0ms or 15ms. Odd. A little research reveals the culprit: Windows. (Although apparently fixed in Windows 7.) How to address this?
If I am simply timing code I'll use System.nanoTime(), but in my case I am relying on a software clock buried deeply in a library which calls System.currentTimeMillis(). But I can fix that code!
I need to continue using wall-clock millis but I'd like actual millisecond granularity. My solution:
class ActualMillis {
private final long millis = System.currentTimeMillis();
private final long nanos = System.nanoTime();
public long currentTimeMillis() {
return millis + (System.nanoTime() - nanos) / 1000000;
}
} The idea here is to record a snapshot of "now" at construction, and then use offsets from the snapshot on query. This addresses two issues at once:
But still some things bother me:
System.nanoTime() is difficult. I believe dividing by 1,000,000 obliterates problems like backwards time, but I cannot prove it (although Java 7 seems to address this).Other solutions very welcome.
I'm embarrassed to have missed this when version 1.0 came out: JetBrains MPS 1.1: Performance Improvements and Easier Debugging. Or, from the firehose.
I ran into a great question on stackoverflow while researching a concurrency question: how to you upgrade a read lock to a write lock?
The answer is easy: you can't. Trying to do so gives you deadlock.
The discussion covers a DAG data structure, but I wanted to try a simpler case.
Say you have an idempotent "resource" (intentionally vague):
public interface Resource {
void something() throws IOException;
} The resource can spoil, and you want try another instance automatically. The obvious thing:
public class RetryResourceFacade
implements Resource {
private Resource resource;
public RetryResourceFacade() {
refreshResource();
}
public void something() {
while (true) {
try {
resource.something();
return;
} catch (final IOException e) {
refreshResource();
}
}
}
private void refreshResource() {
while (true) {
try {
resource = newResource();
return;
} catch (final IOException e) {
// try another one
}
}
}
public static Resource newResource()
throws IOException {
return null; // unlikely in real life
}
} Essentially when a resource spoils, you try another one until one works. But this is horrible for concurrent code: how to fix it?
public class RetryResourceFacade
implements Resource {
private final Object lock = new Object();
private volatile Resource resource;
public RetryResourceFacade() {
refreshResource();
}
public void something() {
synchronized(lock) {
while (true)
try {
resource.something();
return;
} catch (final IOException e) {
refreshResource();
}
}
}
}
private void refreshResource() {
while (true) {
try {
resource = newResource();
return;
} catch (final IOException e) {
// try another one
}
}
}
public static Resource newResource()
throws IOException {
return null; // unlikely in real life
}
} Well, better, but still—do I really want to single-thread calls to something()? I can do yet better still:
public class RetryResourceFacade
implements Resource {
private final Lock readLock;
private final Lock writeLock;
private volatile Resource resource;
public RetryResourceFacade() {
final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
readLock = lock.readLock();
writeLock = lock.writeLock();
refreshResource();
}
public void something() {
while (true) {
readLock.lock();
try {
resource.something();
readLock.unlock();
return;
} catch (final IOException e) {
readLock.unlock();
refreshResource();
}
}
}
private void refreshResource() {
writeLock.lock();
while (true) {
try {
resource = newResource();
writeLock.unlock();
return;
} catch (final IOException e) {
// try another one
}
}
}
public static Resource newResource()
throws IOException {
return null; // unlikely in real life
}
} By introducing read/write locks, I can let many callers use something() but single-thread refreshing the resource (I do not want several callers refreshing resource at once).
But there is one final problem. What happens when two callers are both in something() and the same resource spoils? They both race to refreshResource(), one of them wins and gets a valid resource, but the other then throws that good one away and gets another new resource. Wasteful and embarrassing. The final solution:
public class RetryResourceFacade
implements Resource {
private final Lock readLock;
private final Lock writeLock;
private volatile Resource resource;
private volatile boolean valid;
public RetryResourceFacade() {
final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
readLock = lock.readLock();
writeLock = lock.writeLock();
refreshResource();
}
public void something() {
while (true) {
readLock.lock();
try {
resource.something();
readLock.unlock();
return;
} catch (final IOException e) {
valid = false;
readLock.unlock();
refreshResource();
}
}
}
private void refreshResource() {
writeLock.lock();
if (valid) {
// Another caller already fixed resource
writeLock.unlock();
return;
}
while (true) {
try {
resource = newResource();
valid = true;
writeLock.unlock();
return;
} catch (final IOException e) {
// try another one
}
}
}
public static Resource newResource()
throws IOException {
return null; // unlikely in real life
}
} Only refresh the resource if it is invalid. This is a little bit like handling spurious wakeup in that several threads compete for the resource, but only the first one gets to actually do something with it.
resource and valid as volatile to ensure "publish" semantics (Jeremy Mason has a great post on this), otherwise anything could happen (really).UPDATE: Thanks to Darren Accardo for key ideas in this post; his threading is stronger than mine!
I like to brag about my ex-coworkers at ThoughtWorks, they are some pretty amazing folks. But I should not overlook my coworkers at JPMorgan, who are also pretty amazing folks.
Take this great post on OSGi history from Neil Bartlett who was at JPMorgan in London. I think I've been pretty lucky at picking employers and coworkers (with one huge exception).
(JPMorgan is the kind of company where its easy to connect to others across the globe. It is unlucky I never worked with Neil.)
A beautiful post from Michael Norton explaining how to optimize agile pairing, though he does not so in those words.
The answer? Follow the (simple) math: pair your weaker teammates with the solid middle to strengthen them, and let your high-fliers continue to soar.
Alberto Gutierrez has a great list of development principles any agilist should take to heart. I like that the list is organized in such a way I can easily present it to management.
I also enjoy his post formatting and layout — it's like reading a good newspaper with modern typography. Into my reader feed goes Alberto.
Kyle Cartmell has a year-old post entitled Five Common java.lang.Process Pitfalls that recently turned up as "new" on DZone. The post is really top flight and will set you straight if you need to fork processes from inside Java.
James Shore writes about Large-scale Agile. Half a decade ago I was at ThoughtWorks and heard tale of massive agile undertakings in the UK by TW under the aegis, "distributed agile". I never experienced it first hand (but I can read about one such project) and I'd love to hear from any other TWers or alums who worked firsthand on these.
(Thanks to Rod Coffin for pointing out Shore's post to me.)
Martin Fowler writes about blue-green deployment, a technique I will try out for my next production project. With posts like these, Fowler shows why ThoughtWorks continues to turn out brilliant agilists.