I know that this subject is slightly "Played Out", but I am still terribly confused. I have a class with properties that will be updates by multiple threads and I am trying to allow the properties to be updated in a Threadsafe manner.
Below, I have included a few examples of what I have tried thus far (the class is contained within a BindingList so its properties call a PropertyChangingEventHandler event).
Method 1 - Doubles
private double _Beta;
public double Beta
{
get
{
return _Beta;
}
}
private readonly BetaLocker = new object();
public void UpdateBeta(double Value)
{
lock (BetaLocker)
{
_Beta = Value;
NotifyPropertyChanged("Beta");
}
}
Method 2 - Ints
private int _CurrentPosition;
public int CurrentPosition
{
get
{
return _CurrentPosition;
}
}
public void UpdatePosition(int UpdateQuantity)
{
Interlocked.Add(ref _CurrentPosition, UpdateQuantity);
NotifyPropertyChanged("CurrentPosition");
}
Basically - is the current way that I am creating properties completely threadsafe for both ints and doubles?
You have to ask yourself what it means to be Thread Safe (yes, it's a link to wikipedia and it's blacked out ^_^):
A piece of code is thread-safe if it only manipulates shared data structures in a manner that guarantees safe execution by multiple threads at the same time. There are various strategies for making thread-safe data structure
So now you have to determine if your code guarantees safe execution if executed by multiple threads: the quick answer is that both of your code samples are thread safe! However (and this is a big one), you also have to consider the usage of the object and determine if it is Thread Safe also... here is an example:
if(instance.Beta==10.0)
{
instance.UpdateBeta(instance.Beta*10.0);
}
// what's instance.Beta now?
In this case you have absolutely no guarantee that Beta will be 100.0 because beta could have changed after you checked it. Imagine this situation:
Thread 2: UpdateBeta(10.0)
Thread 1: if(Beta == 10.00)
Thread 2: UpdateBeta(20.0)
Thread 1: UpdateBeta(Beta*10.0)
// Beta is now 200.0!!!
The quick and dirty way to fix this is to use a double-checked lock:
if(instance.Beta==10.0)
{
lock(instance)
{
if(instance.Beta==10.0)
{
instance.UpdateBeta(instance.Beta*10.0);
}
}
}
The same is true for CurrentPosition.
Related
#Builder
public class X {
#Nonnull String a;
#Nonnull String b;
}
main () {
X.XBuilder builder = X.builder();
//thread 1
CompletableFuture.runAsync(()-> {
builder.a("some");
});
//thread 2
CompletableFuture.runAsync(()-> {
builder.b("thing");
});
}
Here the same object is being accessed and modified at the same time.
So will this code be thread safe?
Usecase is like wants to call multiple api's, each api results is to populate the fields of class X.
If you want to know how the stuff that Lombok generates works, you can always use the delombok tool.
With regard to thread safety of #Builder, you will see that you can in fact access a builder instance from multiple threads, but only under these constraints:
Don't call the same field setter from different threads. Otherwise you'll never know which value makes it to the builder eventually.
Make sure that all value-setting threads have terminated before you call build(). (If you want to call build() in a thread, too, make sure you create this thread after all value-setting threads have terminated.)
This is necessary because #Builder wasn't designed for concurrency (as that's not something you typically do with a builder). In particular, #Builder does not use synchronization or volatile fields, so you have to create a happens-before relation for all setter calls with the build() call.
I have read this article (https://blogs.msdn.microsoft.com/oldnewthing/20040308-00/?p=40363), so i have written such code to protect the initialization of a local static object to be thread-safe.
I fear of making mistakes (some logic errors) or performance issues, so could you review my code or give me some hints to make it better, please.
My code (Platform is Windows):
static MyClass& get(void)
{
enum { uninitialized = 0, initializing, initialized };
static long state; // this will initialize to zero becuase it's static
// lock and intitialize or wait until intitialized
for(bool condition = false; !condition;)
{
switch(compareExchange32(&state, initializing, uninitialized))
{
case uninitialized: // object has to be created
case initialized: // object is already created
condition = true;
break;
default: // we wait for creation
break;
}
}
// Thread-safe initialization of object ?
static MyClass _instance;
// release lock
exchange32(&state, initialized);
return _instance;
}
Note that the C++ standard now supports thread-safe init of statics, no need for hand-hacking. See e.g. link to description of compiler impl of thread-safe static singleton
and
SO answer with link to standard
I now see that you have updated your question and that you do not have a C++11 compiler. But can you not use e.g. pthreads or similar to avoid hand -hacking synchronization? If performance is critical, maybe you have to use atomic ops.
class MyClass
{
private static MyClass obj;
public static MyClass getInstance()
{
if(obj==null)
{
obj = new MyClass();
}
return obj;
}
In the above java code sample, because obj is a static variable inside the class,
will getInstance still be non-thread safe? Because static variables are shared by all threads, 2 simultaneous threads shall be using the same object. Isnt it?
Vipul Shah
Because static variables are so widely shared they are extremely un-thread safe.
Consider what happens if two threads call your getInstance at the same time. Both threads will be looking at the shared static obj and both threads will see that obj is null in the if check. Both threads will then create a new obj.
You may think: "hey, it is thread safe since obj will only ever have one value, even if it is initialized multiple times." There are several problems with that statement. In our previous example, the callers of getInstance will both get their own obj back. If both callers keep their references to obj then you will have multiple instances of your singleton being used.
Even if the callers in our previous example just did: MyClass.getInstance(); and didn't save a reference to what MyClass.getInstance(); returned, you can still end up getting different instances back from getInstance on those threads. You can even get into the condition where new instances of obj are created even when the calls to getInstance do not happen concurrently!
I know my last claim seems counter-intuitive since the last assignment to obj would seem to be the only value that could be returned from future calls to MyClass.getInstance(). You need to remember, however, that each thread in the JVM has its own local cache of main memory. If two threads call getInstance, their local caches could have different values assigned to obj and future calls to getInstance from those threads will return what is in their caches.
The simplest way to make sure that getInstance thread safe would be to make the method synchronized. This will ensure that
Two threads can not enter getInstance at the same time
Threads trying to use obj will never get a stale value of obj from their cache
Don't try to get clever and use double checked locking:
http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html
Good explanation can be found here:
http://en.wikipedia.org/wiki/Singleton_pattern
The wiki article highlights various thread-safe approaches along with some of their pros and cons.
in this case getInstance() is not thread-safe, even if you use static variable. only synchronization makes this thread-safe.
The following example shows a weird thread save modified single ton pattern which supports generics as well.
To have it just thread save and synchronization save just take the synchronized block and the transient and volatile keywords.
Notice, that there is a double check, the synchronized block is inside an if. This brings more performance, because synchronized is expensive.
Of course for a real singleton do not use maps, I said it is a modified one.
public class Edge<T> {
#SuppressWarnings({"unchecked"})
private static transient volatile HashMap<Object,HashMap<Object, Edge>> instances = new HashMap<Object, HashMap<Object,Edge>>();
/**
* This function is used to get an Edge instance
* #param <T> Datatype of the nodes.
* #param node1, the source node
* #param node2, the destination node
* #return the edge of the two nodes.
*/
#SuppressWarnings({"unchecked"})
public static <T> Edge<T> getInstance(T node1, T node2){
if(!(instances.containsKey(node1) && instances.get(node1).containsKey(node2))){
synchronized (Edge.class) {
if(!(instances.containsKey(node1) && instances.get(node1).containsKey(node2))){
Edge<T> edge = new Edge<T>(node1, node2);
if(!instances.containsKey(node1)){
instances.put(node1, new HashMap<Object, Edge>());
}
instances.get(node1).put(node2, edge);
}
}
}
return (Edge<T>)instances.get(node1).get(node2);
}
public class Singleton{
private static transient volatile Singleton instance;
public static Singleton getInstance(){
if(instance==null)synchronized(Singleton.class){
if(instance==null){
instance = new Singleton();
}
}
return instance;
}
private Singleton(){
/*....*/
}
}
Page 182:
http://books.google.com/books?id=GGpXN9SMELMC&printsec=frontcover&dq=design+patterns&hl=de&ei=EFGCTbyaIozKswbHyaiCAw&sa=X&oi=book_result&ct=result&resnum=2&ved=0CDMQ6AEwAQ#v=onepage&q&f=false
Think this can be tagged as answered now.
class MyClass
{
private static MyClass obj;
private MyClass(){
// your initialization code
}
public static synchronized MyClass getInstance()
{
if(obj==null)
{
obj = new MyClass();
}
return obj;
}
I'll agree with #Manoj.
I believe the above will be one of the best methods to achieve singleton object.
And synchronization makes the object thread safe.
Even, it's static :)
I have an example piece of code the illustrates issues in my code when GC.Collect is carried out on a class having a ReaderWriterLockSlim member variable. The GC.Collect takes between 2 and 3 seconds to run. I need to carry out GC at regular intervals because my applicaton is extremely memory intensive.
namespace WpfApplication12
{
public class DataItem
{
private readonly ReaderWriterLockSlim m_propertyLock = new ReaderWriterLockSlim();
public DataItem()
{
}
}
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
List<DataItem> dataItemList = new List<DataItem>();
for (int i = 0; i < 100000; i++)
{
dataItemList.Add(new DataItem());
}
Debug.WriteLine(DateTime.Now.ToString());
GC.Collect();
Debug.WriteLine(DateTime.Now.ToString());
}
}
}
Has anyone had similar problems?
Thanks
Ian
I'd ask if you really need a ReaderWriterLockSlim for each of your DataItem classes?
Seems like bad design to me to have that many handles floating about. After-all, that's what will be causing the delay...
The memory issue may be caused if the readerwriterlockslim is called from multiple threads. I believe it will store some information of the threads which can cause the memory consumption to bloat. I would recommend trying to figure out a solution where you can bring down the number of thread that are calling the readerwriterlockslim.
[ThreadStatic]
private static Foo _foo;
public static Foo CurrentFoo {
get {
if (_foo == null) {
_foo = new Foo();
}
return _foo;
}
}
Is the previous code thread safe? Or do we need to lock the method?
If its ThreadStatic there's one copy per thread. So, by definition, its thread safe.
This blog has some good info on ThreadStatic.
A [ThreadStatic] is compiler/language magic for thread local storage. In other words, it is bound to the thread, so even if there is a context switch it doesn't matter because no other thread can access it directly.