Sunday, December 22, 2024
Riffs from an overheated mind

Tags


Blogroll


Categories



Java Concurrency For Dummies: Pt 1 – The basics

July 31st, 2009 by hashbrown

During my recent week at the JavaOne conference, I attended several sessions dealing with issues of concurrency in programming. What started as a cursory interest, turned into a strong desire to really understand these problems at a deeper level. But I’m still really a noob when it comes to this stuff, so I figure this is a great time to try to explain it to other beginners.

Ok, let’s start with the basics, what is concurrency and why should you care? Well according to Wikipedia concurrency is

a property of systems in which several computations are executing simultaneously, and potentially interacting with each other. The computations may be executing on multiple cores in the same chip, preemptively time-shared threads on the same processor, or executed on physically separated processors.

Unless you’re writing applications that only have a few simultaneous users, chances are you will use the threading features of java to try and take advantage of the performance benefits of asynchronous processing. Even if you are writing a simple MVC style web app, that servlet container is going to be multi-threaded and you could encounter concurrency issues in your servlet code. The problem is, when we’re coding our app, it’s only ever exercised in a single-user scenario. And you can’t really write unit tests to check the behavior of multi-threaded areas of your code. Therefore, concurrency issues tend to not be identified during testing. Usually they appear as strange, random bugs during periods of heavy load, and cannot be reliably reproduced. Awesome. I love those.

So how do we identify the areas of our application that are susceptible to concurrency issues, and how do we code for them? Those are some pretty tough questions, I’ve found. Maybe by the end of this series we’ll have some answers. In the simplest of terms, managing concurrency means managing the shared state in your application, more specifically, mutable shared state. That really means any instance or static class level fields that are not declared as final. (There are some nuances to the use of the final keyword, but let’s keep it easy for now).
To control concurrency issues, follow 3 rules:

  • Don’t share state across threads. This is done by encapsulating your state. In the simplest example, this means that class fields are private and access is limited to one or two methods. This will make it easier to create code that is thread-safe.
  • Make your state immutable. If the value of your fields cannot be changed, you are already thread-safe! Consider exposing read-only versions of your objects when possible.
  • Finally, synchronize access. Only allow a single thread to access your state at any given time. Most concurrency discussion centers around locking and synchronization.

What does it mean to synchronize access? Synchronization is about controlling access to state and is handled primarily through locks. Proper synchronization guarantees 2 things:

  • Mutual Exclusion – this guarantees that only one thread can hold a given lock, and therefore only one thread has access to the locked state(data).
  • Visibility – this guarantees that as a thread releases a lock, any changes made to shared variables, the mutable shared state, will be immediately seen by all threads, most importantly the next thread acquiring the lock. This ensures that no threads see stale data.

So, concurrent programming in a nutshell:

Limit the mutable state (data that can be changed) in your objects. When allowing others to access and change your objects state, control that state using proper synchronization.

So that’s the absolute basics on concurrency, but what about Java?
The fundamental power of java is its memory model and the threading facilities that are built into the language. Along with thread support are many mechanisms to correctly handle concurrent operations. And this will be the subject of the rest of this blog series. Stay tuned.

Posted in geek stuff, programming | Comments Off on Java Concurrency For Dummies: Pt 1 – The basics

Java Interview Puzzler

June 18th, 2009 by hashbrown

This is a puzzler we created at my work to use as an interview problem. I had a fun time taking it myself, and got it wrong the first time! It was designed to mimic some bad legacy code you might encounter when working on a large aging system, that has passed through many hands. Terrible coding practices, no javadocs or comments, etc. You are tasked to figure out what the heck it does.
First – does it compile? If not, how do you fix it?
Second – If it compiles, what is the output?

I’ll answer questions and post the solution in the comments.

package crazy;

public class Timing extends R {
    public static final Integer t = new Integer("4");


    public static void main(String[] args) {
        Timing t = new Timing(11);

        System.out.print(t.foo);
        bat(t);
    }

    void fob() { fod(); }

    public Timing(int value) {

        super();
        foo = foo % value;
        bar();
    }

    static {
        System.out.print("6");

    }

    private void bar() {
        new Baz().bar(5);
        tr = "2";
    }

    private int foo = 25;


    static void r() { System.out.println("1"); }
}

abstract class R {

    String tr = "9";

    static void bat(R r) {
        r.fob();
        System.out.print(r.tr);

    }

    private int negate(int bam) {
        return bam * -1;
    }


    public R() {
        System.out.print("7");
    }

    void fod() { System.out.print((int)Math.floor(.99)); }


    protected final int t() {
        return 5;
    }

    class Baz {

        void bar(int fob) {
            if (fob == 9)
                System.out.print(String.valueOf(fob++));

                System.out.print(String.valueOf(negate(fob++)));
            if (fob == 5)
                System.out.print(String.valueOf(fob+=2));

        }
    }

    static {
        System.out.print("8");
    }

    abstract void fob();

}

Posted in geek stuff, programming | Comments Off on Java Interview Puzzler

My Week At JavaOne

June 5th, 2009 by hashbrown

I just returned home from a week in San Francisco at the JavaOne conference, I mean literally like 2 hours ago. This is the first time I’ve been to any conference like this, and I had a great time! The scale of this thing is really impressive, I mean it’s huge. The planning and logistics that go into putting on a conference of this size just amazes me. It felt like they really went all out, all the small details were handled, and you could see the effort they put into making it a special experience.

I had originally registered for tech sessions Tuesday – Thursday, but Thursday night I just wasn’t ready for it to end, and ended up cramming 2 more sessions in on Friday morning before jumping in a cab for the airport. I literally was in a cab 15 minutes after my final session.
Overall, I attended 19 technical sessions over 3 1/2 days, plus the general session keynotes.

I attended sessions on the different dynamic scripting languages that run on the JVM, many on concurrency, and then some on how to use those dynamic languages to solve concurrency problems. I had sessions on Spring, and REST using JAX-RS, sessions on unit testing and some of the tools available. I had a session on defective java with the man behind FindBugs, and a session on Effective Java (2nd Edition)
with one of the absolute rock-stars of the java world, Joshua Bloch. My session on Spring 3.0 was given by THE man behind Spring, Rod Johnson. My sessions on Lift and Clojure were both given by the creators of the language, and the session on JAX-RS was given by the writers of the specification. When I went to hear about how the Google App Engine now supports java, it was directly from the 3 guys responsible for it. I mean, talk about getting it from the source! That google session led to a very late night with my co-worker as we sat in the bar playing with the new sdk until 1am! Read the rest of this entry »

Posted in geek stuff, programming | Comments Off on My Week At JavaOne