Rebecca
Rebecca

Reputation: 710

Hot-Swapping Java Classes

I've been working on a small Java-based online game, which, although not finished, I want to release it at some point. I don't forsee it being finished anytime soon, however, all that's missing are some continued story parts. I thought about patching updates into the game through the internet connection (as most games do) - but I wanted to be clever with it and use some form of class hot-swapping to patch in updates without having to re-load the game.

Originally, I thought that JRebel would work for this purpose, however, as far as I know, it's not easily invoked from within the application itself.

The way I envision this process is:

  1. Server tells client that there's an update available
  2. Client downloads ZIP/JAR/whatever and extracts it
  3. Client loads in 'package class' which modifies the running image (Client has specially constructed parts of it designed to handle loading in additional classes & possibly overwriting existing classes.)
  4. 'package class' handles overwriting of in-memory class representations.

The part that's troubling me is that if I have an object, i.e.

    //Something that's called when the app loads up
    CustomClass drawClass = new CustomClass();
    drawClass.setContext(Context.MAIN);
    //...More calls that set up drawClass

I want to be able to modify CustomClass and have it reflected in all instances of CustomClass. The only reason I am hopeful for this is that I could build in to each class a "copyMe" thing that essentially serializes it - which could be loaded into the new class.

Can I do this? If so, how?

Upvotes: 2

Views: 141

Answers (2)

ddyer
ddyer

Reputation: 1786

I think you're buying a world of hurt if you want to allow updates to arbitrary parts of a running program. I'm not saying it's impossibe, only that it's very difficult to get right, especially considering missing or failed intermediate updates.

Instead, use the "suspend game/resume game" functionality, wrapped up so it's invisible to the user, to transition cleanly from the old version to the updated version.

Upvotes: 1

Rob Audenaerde
Rob Audenaerde

Reputation: 20069

I think you might tackle some of the required functionality using SPI

In your code you can build a custom classloader that uses the implementation that is found using the ServiceLoader.

Although I think you need to find a custom serialization that you can reuse over these classes. For example you can use gson and serialize the interesting fields to json. Newer implementations can deserialize and you got support for versioning etc.

Upvotes: 1

Related Questions