Thursday, October 29, 2009

Marker Interface in Java: what, why, uses, etc.

What are Marker Interfaces in Java?

An empty interface having no methods or fields/constants is called a marker interface or a tag interface. This of course means if the interface is extending other interfaces (directly or indirectly) then the super interfaces must not have any inheritable member (method or field/constant) as otherwise the definition of the marker interface (an entirely empty interface) would not be met. Since members of any interface are by default 'public' so all members will be inheritable and hence we can say for an interface to be a marker interface, all of its direct or indirect super interfaces should also be marker. (Thanks marco for raising the point. I thought it was obvious, but mentioning all this explicitly would probably help our readers.)

There are few Java supplied marker interfaces like Cloneable, Serializable, etc. One can create their own marker interfaces the same way as they create any other interface in Java.

Purpose of having marker interfaces in Java i.e., why to have marker interfaces?

The main purpose to have marker interfaces is to create special types in those cases where the types themselves have no behavior particular to them. If there is no behavior then why to have an interface? Because the implementor of the class might only need to flag that it belongs to that particular type and everything else is handled/done by some other unit - either internal to Java (as in the case of Java supplied standard marker interfaces) or an app specific external unit.

Let's understand this by two examples - one in which we will discuss the purpose of a standard Java interface (Cloneable) and then another user-created marker interface.

What purpose does the Cloneable interface serve?

When JVM sees a clone() method being invoked on an object, it first verifies if the underlying class has implemented the 'Cloneable' interface or not. If not, then it throws the exception CloneNotSupportedException. Assuming the underlying class has implemented the 'Cloneable' interface, JVM does some internal work (maybe by calling some method) to facilitate the cloning operation. Cloneable is a marker interface and having no behavior declared in it for the implementing class to define because the behavior is to be supported by JVM and not the implementing classes (maybe because it's too tricky, generic, or low-level at the implementing class level). So, effectively marker interfaces kind of send out a signal to the corresponding external/internal entity (JVM in case of Cloneable) for them to arrange for the necessary functionality.

How does JVM support the 'cloning' functionality - probably by using a native method call as cloning mechanism involves some low-level tasks which are probably not possible with using a direct Java method. So, a possible 'Object.clone' implementation would be something like this:-

public Object clone() throws CloneNotSupportedException {

if (this implements Cloneable)

return nativeCloneImpl();


throw new CloneNotSupportedException();


Anyone wondered as to why and when do we get 'CloneNotSupportedException' exception at compile-time itself? Well... that's no trick. If you see the signature of the 'Object.clone()' method carefully, you will see a throws clause associated with it. I'm sure how can you get rid of it: (i) by wrapping the clone-invocation code within appropriate try-catch (ii) throwing the CloneNotSupportedException from the calling method.

What purpose does a user-defined marker interface serve? It can well serve the same purpose as by any standard marker interface, but in that case the container (the module controlling the execution of the app) has to take the onus of making sure that whenever a class implements that interface it does the required work to support the underlying behavior - the way JVM does for Cloneable or any other standard marker interface for that matter.

Defining an user-defined marker interface in Java

Let's define a user-defined marker interface. Let's say there is an app suporting a medical store inventory and suppose you need a reporting showing the sale, revenue, profit, etc. of three types of medicines - allopathic, homeopathic, and ayurvedic separately. Now all you need is to define three marker interfaces and make your products (medicines) implement the corresponding ones.

public interface Allopathic{}
public interface Homeopathic{}
public interface Ayurvedic{}

In your reporting modules, you can probably get the segregation using something similar to below:-

for (Medicine medicine : allMedicines) {
if (medicine instanceof Allopathic) {
//... update stats accordingly
else if (medicine instanceof Homeopathic) {
//... update stats accordingly
else if (medicine instanceof Ayurvedic) {
//... update stats accordingly
else {
//... handle stats for general items

As you can see the medicines themselves don't need to implement any specific behavior based on whether they are allopathic, homeopathic, or ayurvedic. All they need is to have a way of reflecting which category they belong to, which will in turn help the reporting modules to prepare the stats accordingly.

Now this can be done by having a flag as well... yeah, sure it can be. But, don't you think tagging a class makes it more readable than having a flag indicating the same. You kind of make it an implementation-independent stuff for the consumers of your classes. If your class implements an interface, it becomes part of the class signature of the published API. Otherwise, you would probably handle the situation by having a public final field having the flag set up at the time of instantiation - final because you would not like others to change it. I guess going the marker interface way would probably make more sense in many such situations.

Another advantage of going via marker interface way is that at any point of time you can easily cast the objects of the implementing classes. Again it's not that if you go via public final approach, you can't do that. You can very well do, but casting might look a cleaner approach in many situations.

The bottom-line is there will hardly be any enforced need for a designer/developer to go via that way as there can be possible alternatives, but marker interfaces can surely be a preferred choice for some in some cases.

Note: Annotations are considered as another possible (quite popular as well) alternative to marker interfaces. Read more about them in this article - Annotations in Java >>

Liked the article? Subscribe to this blog for regular updates. Wanna follow it to tell the world that you enjoy GeekExplains? Please find the 'Followers' widget in the rightmost sidebar.


Tuesday, October 13, 2009

Connecting to an HTTP Web Service from VBA via Proxy

Connecting to an HTTP Web Service from VBA Excel via a Proxy Server

Though MSDN suggests using stubs generated from the WSDL by MS Soap Toolkit for connecting to an HTTP Web Service from within VBA Excel, but it might not work as you would like it to, especially for a SOA-compliant web service and particularly in the cases where you need to access the service via a Proxy Server.

I have used the SOAP Connector called 'httpConnector30' successfully to connect to an HTTP Web Service without any issues. This connector is a part of the Microsoft SOAP Library named MSSOAPLib30 and you got to make sure that this library is referenced in your Excel installation. If it's not already there in your excel, just add the corresponding DLL and you're done.

Using httpConnector30 is different from consuming a Web Service by creating the stubs using MS Soap Toolkit. 'httpConnector30' requires you to specify the actual Web Service URL whereas the toolkit asks you the WSDL url and creates stubs accordingly, which you use in your VBA code. I personally think using 'httpConnector30' is easier and more straightforward if you have the service url.

Before we jump on to the code listed below, let's understand what all the code does broadly:-

  • Instantiating the SOAP Connector
  • Setting up the Proxy Server and Port (if access needed via Proxy)
  • Setting up the Web Service URL (not WSDL url)
  • Setting up Timeout period for the service call
  • Setting up the SOAP Action i.e., the actual method to be called
  • Beginning SOAP Message and getting connector's Input Stream
  • Building up the SOAP Request (as per your Web Service definition)
  • Sending the SOAP Message (this is where the service call is made)
  • Initializing the SOAP Reader and reading the SOAP Response
Note: in the below code I have not shown the exception handling blocks, which you should include to grab and handle the potential errors gracefully. For example: you should first check the 'connector' as 'Not Nothing' before trying to load the 'reader' with connector's output stream.

Additionally, I've assumed that the first node (except the generic envelope and body) of the SOAP Response is actually a List and hence I've put a loop to iterate through it. 'Set response = reader.RPCResult.childNodes' actually sets the 'response' to the first node of the SOAP Response as read from the reader (which itself is loaded with the connector's output stream).

Just to make your service consumption code robust and independent of the Response Structure changes (like addition of new nodes and/or reordering of nodes), in your client code, you should iterate through all the SOAP Response nodes and compare the current node name with your Service Response node names (you can get them in the service WSDL) and subsequently handle the particular node, say inside an if-block. This will make sure that your code doesn't fail abruptly in case Service Response Structure changes. For example: it will avoid any code failure say because you had written it assuming the first node in the response was a List and let's say the service response structure changes make it the second node in the response - maybe because the service provider needed to add another field in the response and also wished to make that the first field. I know the service provide will certainly let the client developers know about the changes, but if you make your code flexible to such possible changes, nothing like it... right?

Public Sub HTTPConnectivityTest()

'Instantiating the SOAP Connector
Dim connector As New MSSOAPLib30.HttpConnector30

'Setting up the Proxy Server and Port
connector.Property("ProxyServer") = "fully-qualified-proxy-server-or-IPAddress:Port"

'Setting up the Web Service URL
connector.Property("EndPointURL") = "http://web-service-server:port/webservices/SampleService.v1"

'Setting up Timeout period for the service call
connector.Property("Timeout") = 2000 '2 minutes

'Setting up the SOAP Action i.e., the actual method to be called
connector.Property("SoapAction") = "urn:getSampleData"

'Beginning SOAP Message

'Initializing SOAP Serializer with connector's input stream
Dim writer As New MSSOAPLib30.SoapSerializer30
writer.Init connector.InputStream

'Building the SOAP Request - envelope and body
writer.startEnvelope ' <SOAP-ENV:Envelope>
writer.startBody ' <SOAP-ENV:Body>

'Populating the SOAP Request with actual input parameters
writer.startElement "SampleServiceRequest", "service namespace", , "s3" ' <SampleServiceRequest>

writer.startElement "inputParam1" ' <inputParam1>
writer.writeString "param1 value" ' value of inputParam1
writer.endElement ' </inputParam1>

writer.startElement "inputParam2" ' <inputParam2>
writer.writeString "param2 value" ' value of inputParam2
writer.endElement ' </inputParam2>

writer.startElement "inputParam3" ' <inputParam3>
writer.writeString "param3 value" ' value of inputParam3
writer.endElement ' </inputParam3>

'Populating list-type parameter
writer.startElement "paramList" ' <paramList>

'Adding node #1 to the list-type param
writer.startElement "paramListNode" ' <paramListNode>
writer.startElement "nodeParam1" ' <nodeParam1>
writer.writeString "value1" ' value of nodeParam1
writer.endElement ' </nodeParam1>

writer.startElement "nodeParam2" ' <nodeParam2>
writer.writeString "value1" ' value of nodeParam2
writer.endElement ' </nodeParam2>
writer.endElement ' </paramListNode>

'Adding node #2 to the list-type param
writer.startElement "paramListNode" ' <paramListNode>
writer.startElement "nodeParam1" ' <nodeParam1>
writer.writeString "value2" ' value of nodeParam1
writer.endElement ' </nodeParam1>

writer.startElement "nodeParam2" ' <nodeParam2>
writer.writeString "value2" ' value of nodeParam2
writer.endElement ' </nodeParam2>
writer.endElement ' </paramListNode>

'Population of list-type param ends here
writer.endElement ' </paramList>

'Finishing the SOAP Request
writer.endElement ' </SampleServiceRequest>
writer.endBody ' </SOAP-ENV:Body>
writer.endEnvelope ' </SOAP-ENV:Envelope>

'Sending the SOAP Message (this is where the service call is made)

'Defining SOAP Reader and initializing it with connector's output stream
Dim reader As New MSSOAPLib30.SoapReader30
reader.Load connector.OutputStream

'Parsing the SOAP Response
Dim response As MSXML2.IXMLDOMNodeList

'Setting the response to the first node of the SOAP Response
Set response = reader.RPCResult.childNodes
Dim node As MSXML2.IXMLDOMNode

'Iterating through the first node of SOAP Response knowing it is a list
For Each node In response
Dim nodeName As String
Dim nodeValue As String

nodeName = node.nodeName
nodeValue = node.nodeTypedValue

'Showing the Node Name and Value on Alert Boxes
MsgBox node.nodeName & ": " & node.nodeTypedValue
Next node
End Sub

Liked the article? Subscribe to this blog for regular updates. Wanna follow it to tell the world that you enjoy GeekExplains? Please find the 'Followers' widget in the rightmost sidebar.


Sunday, October 11, 2009

Why wait(),notify() and notifyAll() in the Object class?

Why wait(), notify() and notifyAll() methods have been defined in the Object class?

Java concurrency model uses locks to implement mutually exclusive access to objects in a multi-threaded environment and locks are associated with every object in Java (of type 'Object'), not only with Threads.

, notify/notifyAll methods are used by threads to communicate with each other while trying to access a common object. Putting it differently, objects become a medium via which threads communicate with each other. For example: suppose there is a 'telephone' object, which at one point of time can be used by only one thread. Like every other object in Java, 'telephone' object would also have an intrinsic lock (monitor) associated with it which at one point of time can be acquired by only one thread. Suppose the 'telephone' object requires activation before it can be used and suppose only a few admin threads can activate the 'telephone' object.

As soon as a thread needs access to the 'telephone' object, it checks if the lock on that 'telephone' object is available or not, if yes, it acquires that and checks if the 'telephone' is active or not. If yes, it starts using it otherwise it calls 'wait()' on the telephone object which effectively releases the monitor of the 'telephone' object (eventually to be acquired by one of the admin threads for its activation) and puts the requester thread into the wait-set of the 'telephone' object. The requester thread goes into WAITING state. The way every object in Java has an intrinsic lock associated with it, it has an intrinsic wait-set associated with it as well.

Every other non-admin requester thread goes through the same process as discussed above till one of the admin threads acquire lock on the 'telephone' object and eventually activates it and subsequently calls 'notify()' or 'notifyAll()' on the 'telephone' object. 'notify()' will simply pick one of the threads from the wait-set of the 'telephone' object (which one will be picked is an implementation dependent stuff and Java Language specification doesn't enforce any restriction on which one to be picked) and the chosen thread will now get out of WAITING mode and start trying to acquire the monitor/lock of the 'telephone' object along with any other thread that might be vying to access the 'telephone' at that point of time.

The only difference between 'notify' and 'notifyAll' is that in case of the latter all the threads of the corresponding wait-set are picked and they all start trying to acquire the lock on the object (with any other incoming requester thread) at the same time.

Evidently you see that these three methods are essentially object-related and not thread-related and hence the designers of Java Language considered it wise to put them in the Object class instead of putting them into the Thread class. The usage of the 'object' (in our case 'telephone') is the particular object's prerogative and not that of the requester threads'. Putting these three methods in the Object class helps the objects owning/controlling their usage in a better way as in that case a thread needs to first acquire the lock on the object (kind of getting a license to use the object) and then calling either wait (in case the thread doesn't find the object in the state it would have wished it to be in and hence thought of waiting for some time to let the object become useful for it) or notify/notifyAll to alert other threads waiting on the object once it finishes using the object (of course in the case when the thread find the object useful in its current state).

Additionally, the communication among the interested threads becomes far too easier when the control is kept at the object's level - one common shared resource/medium and all interested threads communicating via it. Not that the communication won't be possible if these methods are kept in the Thread class, but the handling of the communication and usage of the objects in a multi-threaded environment will probably become more complex and less flexible in that case.

Liked the article? Subscribe to this blog for regular updates. Wanna follow it to tell the world that you enjoy GeekExplains? Please find the 'Followers' widget in the rightmost sidebar.