Wednesday, November 02, 2011

Controlling Access to an Object

I ran into this issue while doing XSLT programming. From XSL you can only call the public static methods of a Java class. Now this presents a problem if multiple threads access your XSLT at the same time and your Java class has some state information e.g. a counter that you don't want to share with or overwritten by other threads. The ideal implementation would be to have a singleton Java object the access to which is controlled by a queue. So the singleton instance is created and destroyed between each use.

Singletons are easy to create [1], and since Java 5.0, its become even easier to create one using enum [2] . The issue is about controlling access to the data values of the Java object in a multi-threaded env. If the same singleton instance is used by multiple threads you could still get corrupted data. So how do you ensure that only one thread uses the critical resources of the instance. The java synchronize comes to the rescue. Create a single public method in your singleton and synchronize the method. That's it. Now you can rest assured that only one thread is using your singleton.

References:
1. www.javacoffeebreak.com/articles/designpatterns/index.html
2. stackoverflow.com/questions/70689/efficient-way-to-implement-singleton-pattern-in-java

0 Comments:

Post a Comment

<< Home