Me and OSGi

OSGi is much like a religion. I’ve even come up with the ten commandments of OSGi:
1. the OSGi way is the only way
2. all 3rd party code that you touch must be OSGi compliant
3. everything must be an OSGi bundle
4. every bundle must have a public part (api)
5. every bundle must keep its private parts covered
6. thou may not rely on the start order of your bundles
7. thou may not rely on a service being present
8. other bundles may be loaded and unloaded at any time
9. thou shall use OSGi in every project
10. thou shall bring the ways of OSGi upon the non-believers

Okay, it’s a bit of a stretch, I admit it. What I’m saying though about it being like a religion, is that it demands of you to follow certain rules. But if you look around you, very few people actually follow them. And if you try to follow them, you’ll find it very difficult.

Why is that? You can do your project the OSGi way, but you will use 3rd party code. Which may or may not be OSGi compliant. If it’s not, you’ll have to bundle it yourself. You can use bnd to do so automatically, but that doesn’t always work, especially for larger projects with lots of dependencies. So sooner or later you’ll find yourself spending 1-2 days trying to coerce some library into OSGi form. With maven it would be a 30 second job, but you’re doing OSGi so you’re stuck with that.

That begs the question: why do OSGi? It was initially conceived for embedded systems, which needed 100% uptime and the possibility of updating modules independently of one another, without stopping the system. Is your project about that? Then you have a valid case for OSGi. You aren’t likely to run into the problems I mentioned, since you’ll likely restrict your use of 3rd party code for reasons of size and performance.

However, most of us work on plain old Java applications. Is modularity good? Well yes! Do you need to update modules without restarting the application? No, you don’t. Do you replace service implementations at runtime? No, you don’t. Do you load and unload modules dynamically at runtime? No, you don’t.
That means for most projects the only gain is modularity, for which you pay a hefty price in the complexity of managing dependencies. There are simpler ways to ensure proper modularization.

Some web applications will need to update without downtime, but for those OSGi is not the answer either. If you need high availability, you’ll already have a cluster or a bunch of servers behind a load-balancer, which you can update without taking the application down.

Conclusion: OSGi is good for what it was originally intended for, but a real pain for most other projects.

Windows RTF Editor with Swing

Ever tried using an RTF editor component for Java/Swing? I did, and I was never satisfied with the ones I found. Neither were the users. One of the reasons was that pretty much all of the users were working on Windows and had become accustomed to the native RTF Editor component from the application we were replacing.
So I thought, why not use the Windows component from the Swing application? How hard can it be?
As a note, I’ve only tried this in a private test project, what you’re about to see is no production code.

The Java side is quite succint:

public class RTFEditor {

  {
    System.load("c:\\myRTFEditor\\rtf.dll");
  }

  private static native String showRTFEditor();
}

There’s just the native method that will display a modal dialog with the RTF component and will return the text that the user entered.

Getting to the native stuff (I used VC++ 10 with Visual Studio)

The header file, rtf.h, generated with javah.exe

/* DO NOT EDIT THIS FILE - it is machine generated */
#include
/* Header for class com_me_RTFEditor */

#ifndef _Included_com_me_RTFEditor
#define _Included_com_me_RTFEditor
#ifdef __cplusplus
extern "C" {
#endif

namespace rtf {

  JNIEXPORT jstring JNICALL Java_com_me_RTFEditor_showRTFEditor(JNIEnv *, jclass);
}

#ifdef __cplusplus
}
#endif
#endif

And the implementation, rtf.cpp. I got the string converstion code from Stackoverflow, unfortunately I don’t remember exactly from where.

#include "stdafx.h"
#include "rtf.h"
#include "rtfForm.h"
#include

using namespace std;
using namespace System::Text;
using namespace System::Runtime::InteropServices;

namespace rtf {

  JNIEXPORT jstring JNICALL Java_com_me_RTFEditor_showRTFEditor(JNIEnv * env, jclass)
  {
    rtfForm^ form = gcnew rtfForm();
    //show modal dialog
    form->ShowDialog();
    // Encode the rtf text from the component as UTF8
    array^ encodedBytes = Encoding::UTF8->GetBytes(form->getRtf());

    // prevent GC moving the bytes around while this variable is on the stack
    pin_ptr pinnedBytes = &encodedBytes[0];

    // convert to jstring to return it to java
    jstring jstr2 = env->NewStringUTF(reinterpret_cast<char*>(pinnedBytes));
    return jstr2;
  }
}

You surely noticed a “rtfForm” is referenced here. I used the UI Designer for it, it’s simply a form with a RTF Editor component inside. Here’s the code for it (rtfForm.h).
I won’t include the code for rtfForm.cpp, as it contains just the include for rtfForm.h

#pragma once

namespace rtf {

using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;

///
/// Summary for rtfForm
///

public ref class rtfForm : public System::Windows::Forms::Form
{
  public:
  rtfForm(void)
  {
    InitializeComponent();
  }

  String^ getRtf()
  {
    return this->richTextBox->Text;
 }

  protected:

  ~rtfForm()
  {
    if (components)
    {
      delete components;
    }
  }
  private: System::Windows::Forms::RichTextBox^ richTextBox;
  protected:

  protected:

  private:
  ///
  /// Required designer variable.
  ///

  System::ComponentModel::Container ^components;

  #pragma region Windows Form Designer generated code
  ///
  /// Required method for Designer support - do not modify
  /// the contents of this method with the code editor.
  ///

  void InitializeComponent(void)
  {
    this->richTextBox = (gcnew System::Windows::Forms::RichTextBox());
    this->SuspendLayout();
    //
    // richTextBox
    //
    this->richTextBox->AcceptsTab = true;
    this->richTextBox->Anchor = static_cast((((System::Windows::Forms::AnchorStyles::Top | System::Windows::Forms::AnchorStyles::Bottom)
    | System::Windows::Forms::AnchorStyles::Left)
    | System::Windows::Forms::AnchorStyles::Right));
    this->richTextBox->Font = (gcnew System::Drawing::Font(L"Courier New", 8.25F, System::Drawing::FontStyle::Regular,     System::Drawing::GraphicsUnit::Point,
static_cast(0)));
    this->richTextBox->Location = System::Drawing::Point(1, 3);
    this->richTextBox->Name = L"richTextBox";
    this->richTextBox->Size = System::Drawing::Size(477, 217);
    this->richTextBox->TabIndex = 0;
    this->richTextBox->Text = L"";
    //
    // reForm
    //
    this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
    this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
    this->AutoScroll = true;
    this->ClientSize = System::Drawing::Size(479, 221);
    this->Controls->Add(this->richTextBox);
    this->Name = L"reForm";
    this->Text = L"reForm";
    this->ResumeLayout(false);

    }
  #pragma endregion
  };
}

And here’s a screenshot of it working
rtf

Unused module dependencies

Do you have a large project with a lot of modules? Adding a new dependency between modules is easy, removing one not so. You have to remove it, check that your build still runs, and repeat this for every dependency you suspect is not really needed.

Well, until now. In keeping with the tradition of starting a project and then abandoning it for a new idea, I’ve now developed an Intellij IDEA plugin which does just that – shows you module dependencies which are not needed.

Want to give it a go? Download the prebuilt plugin from github: https://github.com/asocaciu/idea-moduledependencies-plugin/blob/master/UnusedModuleDependencies.jar
Copy it in your IDEA plugins directory, restart IDEA and you’ll find the ‘Find unused module dependencies’ action under the Analyze menu.

Want to contribute? Here’s the code on github: https://github.com/asocaciu/idea-moduledependencies-plugin

Detecting memory allocations with Android ddms

To detect memory allocations you use the ddms tool, which is to be found in your Android SDK directory, under /tools. Start ddms by running:
./ddms

I sometimes get the following error when ddms starts:

Could not open Selected VM debug port (8700). Make sure you do not have another instance of DDMS or of the eclipse plugin running. If it’s being used by something else, choose a new port number in the preferences. Continue reading

Managing Memory when working with Bitmaps

One of the (very few) errors I had with Jumping Jack was an OutOfMemoryError that happened if you went back and forth from the game to the main screen a few times. On  my phone, an HTC Hero, it happened after doing this about 8-9 times, on a friend’s Motorola Milestone/Droid 2 I could do the same 50 times without it happening.

The OutOfMemory always occurred when loading the large background bitmap. The strange thing about it was that ddms only showed around 3 MB of heap memory being allocated, and as you may know, the limit for a process on Android is 16 MB of heap.

Digging deeper (aka. Googling) I found out that the memory for bitmaps is allocated natively and not as part of the heap, and that the 16 MB limit includes heap and non-heap memory. So that’s one elucidated mystery.

The next thing to do was a memory profiling session, to find out where I was leaking the bitmaps. Well, surprise surprise, it turned out I wasn’t! After more research, it turns out that deallocating non-heap memory is a rather difficult task for the Android GC, and that it actually takes two runs of the GC to clear-out things such as memory used by bitmaps (see the 2nd link at the end of the article).  The author recommended constructs such as:

try {
    BitmapFactory.decodeBitmap(…);
} catch (OutOfMemoryError oome) {
    System.gc();
    BitmapFactory.decodeBitmap(…);
}

as well as giving the GC a helping hand now and then by explicitly calling System.gc().

This didn’t help much either, but on further reading I found out there’s a method called recycle() that you can call on a Bitmap, and which frees the memory used for storing the pixel data for it. So this finally solved my problem – I’m now calling recycle on my bitmaps when my activity gets destroyed – no more OOMs.

Relevant links:

http://www.mail-archive.com/android-developers@googlegroups.com/msg82996.html
http://kohlerm.blogspot.com/2010/02/android-memory-usage-analysis-slides.html