What is the difference Between Singleton object and sessionfactory singleton object - thread-safety

As per my knowledge singleton Object is not thread safe and session Factory singleton object is thread safe.
How this possible, Please explain someone.

The singleton pattern is neither thread-safe nor not thread-safe per se. You have to take a look at your specific implementation. The major question is, does it manage state?
If so then you will make sure that no more than one thread is ever allowed to change the state at the same time. That is the same problem global variables are suffering from regarding thread-safety. But there are mechanisms to ensure this safety, one is called mutual exclusion. The event of two threads concurrently modifying the same variable is one the problematic events, there are more to be aware of. Like two threads sequentially modifying a variable, then the question is whos answer counts.
Mutually exclusive events in general and a specific explanation in the java context can be found here (Mutually exclusive events) and here (Oracle concurrency guide) respectively. Global variables are explained here. Stateless and stateful are also good terms to look at regarding concurrency, parallelism and thread-safety.
Back to your question: A factory usually doesn't introduce any state and though can being shared freely between several threads. Instances produced by the factory most probably are stateful and should only be shared between threads after having made them thread-safe.
Important Note:
But don't get me wrong here. Don't forget to always check the implementation of your singletons! In java you can introduce annotations to document your investigations and mark specific code elements as thread-safe. There exist packages wich already define commonly usable annotations to document such behavior, take a look at the apache org.apache.http.annotation. When you use an API it is a good idea to inspect the documentation for such hints.

Session factory object is also implemented using the singleton design pattern.
singleton design pattern can be made as thread safe.
and they have implemented singleton with thread safe for session factory.
when we implement singleton we should make sure whether we need thread safe or not and we should implement acordingly.
see the various implementation of singleton in my blog under design pattern
java guide

Related

COM `IStream` interface pointer and access from different threads

Is it an official COM requirement to any IStream implementation, that it should be thread-safe, in terms of concurrent access to IStream methods through the same interface pointer across threads?
I am not talking about data integrity (normally, reads/writes/seeks should be synchronized with locks anyway). The question is about the need to use COM marshaller to pass IStream object to a thread from different COM apartment.
This is a more general question than I asked about IStream as returned by CreateStreamOnHGlobal, please refer there for more technical details. I'm just trying to understand this stuff better.
EDITED, I have found this info on MSDN:
Thread safety. The stream created by SHCreateMemStream is thread-safe
as of Windows 8. On earlier systems, the stream is not thread-safe.
The stream created by CreateStreamOnHGlobal is thread-safe.
Now I believe, the IStream object returned by CreateStreamOnHGlobal is thread-safe, but there is NO requirement that other IStream implementations should follow this.
No, it isn't. And the accepted answer to the other question is dead wrong. Hans Passant's answer is correct. You should delete this question because it presupposes a falsehood, namely that CreateStreamOnHGlobal returns a thread-safe IStream. It doesn't. You then ask if this is true of other IStream implementations. It isn't.
In computer programming generally, and COM in particular, objects have guarantees they give and guarantees they do not give. If you use an object in conformance with its guarantees, then it will work all the time (barring bugs). If you exceed the guarantees, it may still work most of the time, but this is no longer guaranteed.
Generally in COM, the thread-safety guarantee is given by one of the standard threading models.
See here: http://msdn.microsoft.com/en-us/library/ms809971.aspx
Apartment threaded objects can be instantiated on multiple threads, but can only be used from the particular thread they were instantiated on.
Multi-threaded apartment objects can be instantiated in a multi-threaded apartment and can be used from any of those threads.
"Both"-threaded objects can be instantiated in any thread, and used from any thread.
Note: The threading model belongs to the object not the interface. Some objects supporting IStream may be single-threaded, others may be fully-thread safe. This depends on the code which implements the interface. Because an interface is just a specification, and thread-safety is not something covered by it.
It is always harmless to marshal an interface. If the threading models of the threads are compatible with the object's home thread, you will get the exact same interface pointer back. If they are not compatible, you will get a proxy. But it never hurts to marshal, and unless you know that the objects are compatible, you should always marshal.
However it is always open to an implementer to give additional guarantees.
In the case of CoMarshalInterthreadInterfaceInStream, you are told in the documentation that the returned IStream interface can be used for unmarshalling at the destination thread, using CoUnmarshalInterfaceAndReleaseStream.
That is, you have been given an additional guarantee. So you can rely on that working.
But that does not apply to any other instance of IStream at any time.
So you should always marshal them.

VB6 Is it possible to implement the Singleton design pattern?

Within VB6 is it possible to implement the Singleton design pattern?
Currently the legacy system I work on has a large about of IO performed by multiple instances of a particular class. It is desirable to clean up all these instances and have the IO performed by one instance only. This would allow us to add meaningful logging and monitoring to the IO routines.
There are so many ways to do this, and it depends if this is a multi-project application with different dlls or a single project.
If it is single project and there is a large amount of code that you are worrying about chaning/breaking then I suggest the following:
Given a class clsIOProvider that is instantiated all over the place, create a module modIOProvider in the same project.
For each method / property defined in clsIOProvider, create the same set of methods in modIOProvider.
The implementation of those methods, as well as the instance data of the class, should be cloned from clsIOProvider to modIOProvider.
All methods and properties in clsIOProvider should be chnaged to forward to the implementation in modIOProvider. The class should no longer have an instance data.
(Optional) If the class requires the use of the constructor and destructor (Initialize/Terminate), forward those to modIOProvider as well. Add a single instnace counter within modIOProvider to track the number of instances. Run your initialzation code when the instance counter goes from 0 to 1, and your termination code when the instance counter goes from 1 to 0.
The advantage of this is that you do not have to change the coe in the scores of places that are utilizeing the clsIOProvider class. They are happily unaware that the object is now effectively a singleton.
If coding a proejct from scratch I would do this a bit differently, but as a refactoring appraoch wahat I've outlined should work well.
It's easy enough to only create and use one instance of an object. How you do it depends on your code what it does and where it's called from.
In one process, you can just have a single variable in a global module with an instance, maybe with a factory function that creates it on first use.
If it's shared by multiple process, it complicates things, but can be done with an ActiveX EXE and the Running Object Table.

Address Book thread safety and performance

My sense from the Address Book documentation and my understanding of the underlying CoreData implementation suggests that Address Book should be thread safe, and making queries from multiple threads should pose no problems. But I'm having trouble finding any explicit discussion of thread safety in the docs. This raises a few questions:
Is it safe to use +sharedAddressBook on multiple threads for read-only access? I believe the answer is yes.
For write-access on background threads, it appears that you should use +addressBook instead (and save your changes manually). Do I understand this correctly?
Has anyone investigated the performance impact of making multiple simultaneous queries to Address Book on multiple threads? This should be very similar to the performance of making multiple CoreData queries on multiple threads. My sense is that I would gain little by making parallel queries since I assume they will serialize when they hit SQLLite, but I'm not certain here.
I need to make dozens of queries (some complex) against AddressBook and am doing so on a background thread using NSOperation to avoid blocking the UI (which it currently does). My underlying question is whether it makes sense to set the max concurrent operations to a value larger than 1, and whether there is any danger in doing so if the application may also be writing to AddressBook at the same time on another thread.
Unless an API says it is threadsafe it is not. Even if the current implementation happens to be thread safe it might not be in the future. In other words, do not use AB from multiple threads.
As an aside, what about it being CoreData based makes you think it would be thread safe? CoreData uses a thread confinement model where it is only safe to access a context on a single thread, all the objects from the context must be accessed on the same thread.
That means that sharedAddressBook will not be thread safe if it keeps an NSManagedObjectContext around to use. It would only be safe if AB creates a new context every time it needs to do something and immediately disposes of it, or if it creates a context per thread and always uses the appropriate context (probably by storing a ref to it in the threadDictionary). In either event it would not be safe to store anything as NSManagedObjects since the contexts would be constantly destroyed, which means every ABRecord would have to store an NSManagedObjectID so it could reconstitute the object in the appropriate context whenever it needed it.
Clearly all of that is possible, it may be what is done, but it is hardly the obvious implementation.

What can I access from a BackgroundWorker without "Cross Threading"?

I realise that I can't access Form controls from the DoWork event handler of a BackgroundWorker. (And if I try to, I get an Exception, as expected).
However, am I allowed to access other (custom) objects that exist on my Form?
For instance, I've created a "Settings" class and instantiated it in my Form and I seem to be able to read and write to its properties.
Is it just luck that this works?
What if I had a static class? Would I be able to access that safely?
#Engram:
You've got the gist of it - CrossThreadCalls are just a nice feature MS put into the .NET Framework to prevent the "bonehead" type of parallel programming mistakes. It can be overridden, as I'm guessing you've already found out, by setting the "AllowCrossThreadCalls" property on the class (and not on an instance of the class, e.g. set Label.AllowCrossThreadCalls and not lblMyLabel.AllowCrossThreadCalls).
But more importantly, you're right about the need to use some kind of locking mechanism. Whenever you have multiple threads of execution (be it threads, processes or whatever), you need to make sure that when you have one thread reading/writing to a variable, you probably don't want some other thread barging and changing that value under the feet of the first thread.
The .NET Framework actually provides several other mechanisms which might be more useful, depending on circumstances, than locking in code. The first is to use a Monitor class, which has the effect of locking a particular object. When you use this, other threads can continue to execute, as long as they don't try to lock that same object. Another very useful and common parallel-programming idea is the Mutex (or Semaphore). The Mutex is basically like a game of Capture the Flag between your threads. If one thread grabs the flag, no other threads can grab it until the first thread drops it. (A Semaphore is just like a Mutex, except that there can be more than one flag in a game.)
Obviously, none of these concepts will work in every particular problem - but having a few more tools to help you out might come in handy some day :)
You should communicate to the user interface through the ProgressChanged and RunWorkerCompleted events (and never the DoWork() method as you have noted).
In principle, you could call IsInvokeRequired, but the designers of the BackgroundWorker class created the ProgressChanged callback event for the purpose of updating UI elements.
[Note: BackgroundWorker events are not marshaled across AppDomain boundaries. Do not use a BackgroundWorker component to perform multithreaded operations in more than one AppDomain.]
MSDN Ref.
Ok, I've done some more research on this and I think have an answer. (Let the votes decide if I'm right!)
The answer is.. you can access any custom object that's in scope, however your access will not be thread-safe.
To ensure that it is thread-safe you should probably be using lock. The lock keyword prevents more than one thread executing a particular piece of code. (Subject to actually using it properly!)
The Cross Threading Exception that occurs when you try and access a Control is a safety mechanism designed especially for Controls. (It's easier and probably more efficient to get the user to make thread-safe calls then it is to design the controls themselves to be thread-safe).
You can't access controls that where created in one thread from another thread.
You can either use Settings class that you mentioned, or use InvokeRequired property and Invoke methods of control.
I suggest you look at the examples on those pages:
http://msdn.microsoft.com/en-us/library/ms171728.aspx
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.invokerequired.aspx

Is it safe to manipulate objects that I created outside my thread if I don't explicitly access them on the thread which created them?

I am working on a cocoa software and in order to keep the GUI responsive during a massive data import (Core Data) I need to run the import outside the main thread.
Is it safe to access those objects even if I created them in the main thread without using locks if I don't explicitly access those objects while the thread is running.
With Core Data, you should have a separate managed object context to use for your import thread, connected to the same coordinator and persistent store. You cannot simply throw objects created in a context used by the main thread into another thread and expect them to work. Furthermore, you cannot do your own locking for this; you must at minimum lock the managed object context the objects are in, as appropriate. But if those objects are bound to by your views a controls, there are no "hooks" that you can add that locking of the context to.
There's no free lunch.
Ben Trumbull explains some of the reasons why you need to use a separate context, and why "just reading" isn't as simple or as safe as you might think, in this great post from late 2004 on the webobjects-dev list. (The whole thread is great.) He's discussing the Enterprise Objects Framework and WebObjects, but his advice is fully applicable to Core Data as well. Just replace "EC" with "NSManagedObjectContext" and "EOF" with "Core Data" in the meat of his message.
The solution to the problem of sharing data between threads in Core Data, like the Enterprise Objects Framework before it, is "don't." If you've thought about it further and you really, honestly do have to share data between threads, then the solution is to keep independent object graphs in thread-isolated contexts, and use the information in the save notification from one context to tell the other context what to re-fetch. -[NSManagedObjectContext refreshObject:mergeChanges:] is specifically designed to support this use.
I believe that this is not safe to do with NSManagedObjects (or subclasses) that are managed by a CoreData NSManagedObjectContext. In general, CoreData may do many tricky things with the sate of managed objects, including firing faults related to those objects in separate threads. In particular, [NSManagedObject initWithEntity:insertIntoManagedObjectContext:] (the designated initializer for NSManagedObjects as of OS X 10.5), does not guarantee that the returned object is safe to pass to an other thread.
Using CoreData with multiple threads is well documented on Apple's dev site.
The whole point of using locks is to ensure that two threads don't try to access the same resource. If you can guarantee that through some other mechanism, go for it.
Even if it's safe, but it's not the best practice to use shared data between threads without synchronizing the access to those fields. It doesn't matter which thread created the object, but if more than one line of execution (thread/process) is accessing the object at the same time, since it can lead to data inconsistency.
If you're absolutely sure that only one thread will ever access this object, than it'd be safe to not synchronize the access. Even then, I'd rather put synchronization in my code now than wait till later when a change in the application puts a second thread sharing the same data without concern about synchronizing access.
Yes, it's safe. A pretty common pattern is to create an object, then add it to a queue or some other collection. A second "consumer" thread takes items from the queue and does something with them. Here, you'd need to synchronize the queue but not the objects that are added to the queue.
It's NOT a good idea to just synchronize everything and hope for the best. You will need to think very carefully about your design and exactly which threads can act upon your objects.
Two things to consider are:
You must be able to guarantee that the object is fully created and initialised before it is made available to other threads.
There must be some mechanism by which the main (GUI) thread detects that the data has been loaded and all is well. To be thread safe this will inevitably involve locking of some kind.
Yes you can do it, it will be safe
...
until the second programmer comes around and does not understand the same assumptions you have made. That second (or 3rd, 4th, 5th, ...) programmer is likely to start using the object in a non safe way (in the creator thread). The problems caused could be very subtle and difficult to track down. For that reason alone, and because its so tempting to use this object in multiple threads, I would make the object thread safe.
To clarify, (thanks to those who left comments):
By "thread safe" I mean programatically devising a scheme to avoid threading issues. I don't necessarily mean devise a locking scheme around your object. You could find a way in your language to make it illegal (or very hard) to use the object in the creator thread. For example, limiting the scope, in the creator thread, to the block of code that creates the object. Once created, pass the object over to the user thread, making sure that the creator thread no longer has a reference to it.
For example, in C++
void CreateObject()
{
Object* sharedObj = new Object();
PassObjectToUsingThread( sharedObj); // this function would be system dependent
}
Then in your creating thread, you no longer have access to the object after its creation, responsibility is passed to the using thread.

Resources