Skip to main content

Posts

Showing posts from January, 2010

Garbage Collection, References, Finalizers and the Memory Model (Part 1)

A little while ago, I got asked a question about when an object is allowed to be collected. It turns out that objects can be collected sooner than you think. In this entry, I'll talk a little about that. When we were formulating the memory model, this question came up with finalizers. Finalizers run in separate threads (usually they run in a dedicated finalizer thread). As a result, we had to worry about memory model effects. The basic question we had to answer was, what writes are the finalizers guaranteed to see? (If that doesn't sound like an interesting question, you should either go read my blog entry on volatiles or admit to yourself that this is not a blog in which you have much interest). Let's start with a mini-puzzler. A brief digression: I'm calling it a mini-puzzler because in general, for puzzlers, if you actually run them, you will get weird behavior. In this case, you probably won't see the weird behavior. But the weird behavior is perfectl

A Note on the Thread (Un)safety of Format Classes

I recently got a note on another blog post asking this question: I have a general question on the thread safety and this is not directly related with your blog. I would appreciate if you could post it on your blog. I have a class that has only one static method that accepts two string parameters and does some operation locally (as shown below). Do I need to synchronize this method? public class A {   public static boolean getDate(String str, String str2){     SimpleDateFormat formatter =       new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");     boolean isBefore = false;     Date date1;     Date date2;     try {       date1 = formatter.parse(str);       date2 = formatter.parse(str);       isBefore = date1.after(date2);     } catch (Exception e) {       e.getMessage();     }     return isBefore;   } } Since it had nothing to do with the blog post in question, I'll answer it here. The questioner is clearly asking about the well-documented lack of thread safety of the Format