Lets say we have an object that can be accessed by multiple threads and a global singleton handing out the object’s reference, also accessible by multiple threads.
class Book {
private string title;
public Book(string title) {
this.title = title;
}
public string Title { get { return title; } }
}
class BookstoreSingleton {
public BookstoreSingleton Instance { ... }
public Book Book { get { return this.book; } }
}
Am I correct in thinking that both, the Book.Title and BookstoreSingleton.Book both need thread-safe code?
Your class seems immutable and thread safe. You don’t need to synchronize access to those properties as they can only be read, just make sure that you initialize your singleton only once (the
Instanceproperty) and that you cannot assign it a value a second time.