Garbage collection on Corba and how can a client delete an object? - cross-platform

I am studying CORBA and how IDL maps interfaces to different languages. I read that you can not write constructors and destructors in an IDL interface because objects are not created locally.
My question is:
How can a client delete an object if he does not specify a destructor in the IDL interface, is the server only responsible for deleting objects? Does CORBA provide a garbage collection mechanism/specification or is the language on the server side responsible to do that? If only server is responsible to delete objects how can it be sure that an object should be deleted? Pinging the client?

An e-mail replay from one of my professors:
All lifecycle management of CORBA objects is done
by the object adapter. There is no built-in garbage
collection in CORBA (except that non-persistent objects
are deactivated and removed automatically when the session expires
or hangs, or when a time limit has expired). The servant object
deregistration method deactivate_object() should be explicitly
called on the OA (in server code) to make the OA
deregister/deallocate an object properly
(after awaiting that all possibly still
running calls on that object have terminated).
For simulating remote constructor behavior, a (server-side)
factory object (another CORBA object) should be used.
For simulating remote destructor behavior, the factory
object might provide an explicit destroy method (user-level
memory management controlled by client) or implement
reference counting for garbage collection at user level
(controlled by the server). The latter is tricky
because the ordering with the servant deregistration
call to the OA (deactivate_object()) must be correct.

Related

Ninject: What happens to non-disposable InRequestScope and InTransientScope objects after the HTTP request is finished?

I have searched a lot about these question, here and a lot of other places, but not getting everything I want to know!
From a WebApi project point-of-view, when are InTransientScope objects Created? In the Ninject docs it is stated that such objects are created whenever requested, but in a web api project that handles HTTP requests, the instance is created at the request start time so in this regard it is the same as InRequestScope then?
In a WebApi project, is it okay to use InTransientScope objects knowing that they will never be kept track of by Ninject? If Ninject never keeps track of Transient objects, then what is the purpose of this scope and what happens to such objects after they have been used?
If I declare an object with InRequestScope and that object doesn't implement the IDisposable interface, what happens to such object after the web request has completed? Will it be treated the same way as an InTransientScope object?
Are different scopes to be used for: WebApi controllers, Repositories(that use a InRequestScope Session that is created separately) and Application services?
There's two purposes for scopes:
Only allow one object to be created per scope
(optionally) dispose of the object once the scope ends.
As said, the disposal is optional. If it doesn't implement the IDisposable interface it's not being disposed. There's plenty of usecases for that.
The InTransientScope is the default scope - the one being used if you don't specify another one. It means that every time a type A is requested from the kernel one activation takes place and the result is returned. The activation logic is specified by the binding part that follows immediately after the Bind part (To<...>, ToMethod(...),...).
However, this is not necessarily at the time the web-request starts and the controller is instanciated. For example, you can use factories or service location (p.Ex. ResolutionRoot.Get<Foo>()) to create more objects after the controller has been created. To answer your questions in short:
When: When a request takes place or whenever your code asks for a type from Ninject either directly (IResolutionRoot.Get(..)) or through a factory. As InTransientScope objects are not being tracked they will not be disposed, however, if they are not disposable and the entire request code requests only one IFoo then practically there's is no discernible difference (apart from the slight performance hit due totracking InRequestScope()-ed objects)
As long as you don't need to make sure that instances are shared and/or disposed this is completely fine. After they are not being used anymore, they will get garbage-collected like any object you would new yourself.
When the scope ends ninject will remove the weak reference to the non-IDisposable object. The object itself will not be touched - just like when bound InTransientScope()
That depends on your specific requirements and implementation details. Generally one needs to make sure that long-scoped objects don't depend on short-scoped objects. For example, a Singleton-Service should not depend on a Request-scoped object. As a baserule, everything should be InTransientScope() unless there's a specific reason why it should not be. The reason will dictate what scope to use...

Context and Instance in WCF

I am reading Juval Löwy's Programming WCF Sevices. It mentions:
In WCF, we have Context in which we have the instance. By default, the lifetime of the context is the same as that of the instance it hosts. We can have separate lifetimes for both.
WCF also allows a context to exist without an associated instance at all.
Why would we release the instance and keep the context empty?
Coincidentally I recently read the chapter you're probably referring to. In his book Löwy explains why this may be useful. First he writes:
WCF also allows a context to exist without an associated instance at all. I call this instance management technique context deactivation.
After mentioning this is typically done using an OperationBehavior with a specific ReleaseInstanceMode, he goes on and hints on when you could use this:
You typically apply instance deactivation on some but not all service methods, or with different values on different methods. [...] The reason you typically apply it sporadically is that if you were to apply it uniformly, you would end up with a per-call-like service, in which case you might as well have configured the service as per-call.
So you can use this "deactivation" to ensure only certain methods in a service with sessions behave as if they were part of a per-call service. The abovementioned MSDN article also explains this, in a different wording:
Use the ReleaseInstanceMode property to specify when WCF recycles a service object in the course of executing a method. The default behavior is to recycle a service object according to the InstanceContextMode value. Setting the ReleaseInstanceMode property changes that default behavior. In transaction scenarios, the ReleaseInstanceMode property is often used to ensure that old data associated with the service object is cleaned up prior to processing a method call.
Disconnecting the context from the instance makes sense when:
Instance creation is customized/extended. For example if you are creating your service instance with a custom IInstanceProvider with a dependency injection library (for example Unity) you might want a Unity lifetime manager to handle the service instance lifetime.
Some but not all operations result in an expensive service instance to be invalidated. For example: The service object loads a large expense resource as a part of creation. If the service operations called by the client modify or invalidate the resource, it needs to be disposed and reloaded for the next caller. If the operations don’t invalidate the resource the service instance can be reused by the next caller. (In almost all cases there’s a better way to solve this problem, but WCF allows it).
I’m sure there are additional use cases.

wcf deserializing without memory allocations

I have a WCF service handling a very large number of requests (thousands per second). Each request contains objects, so they get built inside the DataContractSerializer during deserialization. My service processes the messages, and they get cleaned up by the .net garbage collector.
The problem is that garbage collections are causing problems for my service (requests occasionally taking 100+ milliseconds longer than they should). I need to minimize them. So I am looking for a way of using object pooling. In other words, I want the data contract serializer to obtain an object from my object pool (instead of getting one via GetUninitializedObject), and then when I am done processing the message, I would release it back to the pool for cleaning & reuse, thereby avoiding thousands of memory allocations a second.
I've seen this is possible with protobuf-net (Using protobuf-net, is it possible to deserialize a message without allocating memory?) and in fact I'm using protobuf elsewhere, but for this particular situation that is not an option
The DataContractSerializer is sealed and cannot be updated. So unfortunately you would not be able to remove it's call to FormatterServices.GetUninitializedObject.
What you will have to do instead is create your own serializer inheriting from XmlObjectSerializer so that you can fully control instance creation.
The next step is to create a DataContractSerializerOperationBehavior and override the CreateSerializer methods to return your customized serializer.
Last thing to do is remove the default DataContractSerializerOperationBehavior from the endpoint and replace it with the custom one that implements your custom serializer. Carlos Figueira has a post on his blog showing exactly how to do this (go to the section called Real world scenario: using a new serializer).

How to implement IMarshal for custom marshalling interface from out-of-proc server

I am trying to figure out how to implement custom marshalling for an out-of-proc COM server when it fires an event. The server implements the IConnectionPoint interface. One of the methods on the interface that it calls to signal an event takes a pointer to an interface (Call it IMyEventData.). The class that implements IMyEventData in the server also implements IMarshal. When my server fires the event, I get the calls to IMarshal that I expect, including GetMarshalSizeMax, GetUnmarshalClass, and MarshalInterface. So far, so good.
I have implemented the unmarshaller in a separate DLL that is registered on the system. Right after the server handles the MarshalInterface call, my unmarshaller DLL gets loaded into the client, but the calls that I get on its IMarshal interface are not what I expect. The calls are to GetUnmarshalClass, GetMarshalSizeMax, and MarshalInterface. In all of these calls, the context is in-proc, apparently attempting to marshal across apartments rather than process boundaries. I never get the expected call to UnmarshalInterface. When I run both client and server under the debugger, each displays an exception in the output window right after the calls to my unmarshaller's IMarshal interface are made, indicating that an incorrect parameter error (0x80070057) occurred.
Can anyone tell me what I am doing wrong? I had expected my unmarshaller to get a call to IMarshal::UnmarshalInterface so that it would get access to the data that the server supplied in the call to IMarshal::MarshalInterface. I must be missing something basic here.
Thanks.
Wayne
The question is a bit not specific, so the answer will outline the main steps taking place.
Given is an interface pointer on the server side and the pointer needs to get marshaled into foreign apartment. The server COM object implements custom marshaler supposed to be picked up. The client expects the interface pointer to a proxy obtained through custom marshaling.
Server Side
COM queries the COM object in question for IMarshal interface - this succeeds, our object indeed implements it
COM calls IMarshal::GetUnmarshalClass to get CLSID of the class responsible for unmarshaling on client side; this might be the same CLSID of the server object , this could be proxy class CLSID, or proxy factory class CLSID - the idea is that COM requests this via method call, so object is free to return whatever seems appropriate
COM might call IMarshal::GetMarshalSizeMax to prepare a buffer for marshaling data
COM calls IMarshal::MarshalInterface to marhsal the data
Client Side
COM starts here getting eventually external request suggesting that some magic is necessary to spawn a proxy object and obtain COM interface pointer to be given to the controlling/caller application
COM has on hands CLSID of the unmarshaler class and data from the marshaler
COM instantiates a class using the CLSID
COM calls IMarhsal::UnmarshalInterface on the created class and provides IID it eventually wants to obtain
Note that on the last step above COM has the following:
CLSID of the class to instantiate to request interface pointer from
IID of the interface pointer requested
Data produced on server as a result of marshaling process
With all these inputs, the unmarshaler class is expected to return a valid pointer, which might be or might be not the interface of the unmarshaler itself. So you are free to choose whether you want a specialized "factory" unmarshaler class to do create client side object, or you want simply create a new instance and initialize it from marshaling data.

WCF, Unity: Teardown disposable instances

we've set up a WCF service which uses a Unity Container to resolve instances for managing Exchange 2010 Powershell commands. We defined an IExchangePowershell interface which has a concrete implementation that implements IDisposable. After some time we encountered the problem that we couldnt execute powershell commands anymore since the server said there are already too many powershell sessions open. It seems that we never really disposed of our powershell instances. The Dispose() method of the concrete Powershell would take care of closing the runspace and the session. Once I call this in the repository methods, we don't get the errors anymore.
((IDisposable)this.powershell).Dispose();
Now of course I dont want to explicitly call dispose in every repository method. I thought unity could take care of this. Our WCF Instance Provider does this:
public void ReleaseInstance(InstanceContext instanceContext, object instance)
{
container.Teardown(instance);
}
But that doesnt really dispose of the IExchangePowershell instances. Do you have any idea how I could automatically dispose of those instances?
That is actually well known problem in Unity. TearDown method does nothing. If you want to use TearDown you must create custom container extension.
I wrote an article about using object lifetimes managers in Unity and their impact on disposing. If you use default TransientLifetimeManager or PerResolveLifetimeManager the Unity will even don't track existence of your objects so it can't call Dispose. The only lifetime managers which calls Dispose on resolved instances are ContainerControlledLifetimeManager (aka singleton) and HierarchicalLifetimeManager. The Dispose is called when the lifetime manager is disposed.
The solution for you is either use casting and handle Dispose manually as you already did or switch to HiearchicalLifetimeManager and create new subcontainer for each incoming WCF request. Each subcontainer will only handle single request and it will dispose resolved entities with hiearchical lifetime.
There are other ways, for example this article builds a very complex code around Unity to support disposing and TearDown for all resolved objects.
The answer depends on how you register your type / instance with unity. Standard implementation of Teardown does nothing at all.
If you register type then Unity does not store reference to instance it creates - it's up to you to manage it's lifetime and dispose it. If you register instance, then the instance lifetime is managed by unity and is kept until you dispose of the container.
The link below helps to understand a bit better about lifetime management:
http://msdn.microsoft.com/en-us/library/ff648098.aspx
You need to ask yourself when you would like your objects to be disposed. If you know when to call ReleaseInstance, you might as well call IDispose instead of it.
(I'm sorry, I'm not familiar with WCF, so I'm not sure what instance provide is in this context)