Can a thread-safe class contain any public instance fields? - java

Can a thread-safe class contain any public instance fields?

Access modifieres are irrelevant in this context of thread-safety. Of course you can have public fields in a thread safe class, the question you need to ask yourself is : Does this conform to my / a design pattern and what could I possibly achieve from doing this.

When people say that class C is "thread-safe", they usually mean that no interleaving of operations performed on a single instance of the class by multiple threads can leave the instance in an invalid state. (But as Marko says, that's not a formally agreed-upon definition.) So, what are the states of an instance of your class? Which states are valid and which are not valid? Is it possible to change a valid state into an invalid state by updating one of the public fields?
If there is any way that updating a public field can change the state from valid to invalid, then you can't say that the class is generally thread safe, but if that never happens in your application, then maybe the class is thread-safe in the limited context of your application.

Related

WhyJava Bean Pattern is not threadsafe

Joshua Bloch states in Effective Java, 2nd Edition:
One alternative you have to the Telescoping Constructor Pattern is the JavaBean Pattern where you call a constructor with the mandatory parameters and then call any optional setters after:
Pizza pizza = new Pizza(12);
pizza.setCheese(true);
pizza.setPepperoni(true);
pizza.setBacon(true);
The problem here is that because the object is created over several calls it may be in an inconsistent state partway through its construction. This also requires a lot of extra effort to ensure thread safety.
My Question:-
Is above code not thread safe? Am I missing any basic thing?
Thanks in Advance,
Surya
The code that you have shown us involves only one thread, so thread-safety of this code is moot.
If multiple threads could see the Pizza instance, then there are a couple of things to worry about:
Can another thread see the Pizza instance before you have finished initializing it?
When the other thread sees the instance, will it observe the correct values for the attributes?
The first concern is addressed by not "publishing" the references to another thread until you have finished initializing it.
The second one can be addressed by using an appropriate synchronization mechanism to ensure that the changes are visible. This could be done in a number of ways. For example:
You could declare the getters and setters as synchronized methods.
You could declare the (private) variables that hold the attribute values as volatile.
Note that the JavaBean pattern doesn't prescribe how beans are constructed. In your example, you use a no-args constructor and then set fields using setters. You could also implement a constructor which allows you to pass arguments giving (non-default) initial values for properties.
This also requires a lot of extra effort to ensure thread safety
Not really. In this context, it is a small change to make the getters and setters thread-safe. For example:
public class Pizza {
private boolean cheese;
public synchronized /* added */ void setCheese(boolean cheese) {
this.cheese = cheese;
}
public synchronized /* added */ boolean isCheese() {
return cheese;
}
}
The author says textually :
JavaBeans pattern precludes the possibility of making a class immutable and requires a added effort on the part of the programmer
to ensure thread safety.
I think that the author stresses on the fact that it makes no sense to provide methods that prevent the object immutability and may create consistency issues between threads if you object is designed to be immutable : that is it never needs to change once created.
Your question :
Why Java Bean Pattern is not threadsafe ?
Any class that provides a way to mutate a field is not thread safe.
It is true for JavaBeans methods (that generally don't use defensive copy) but it is also true for any mutable class.
Manipulating a no thread safe class is not necessary a problem if you use it in a context where you have no race conditions between threads.
For example this code is thread safe :
Pizza pizza = new Pizza(12);
pizza.setCheese(true);
pizza.setPepperoni(true);
pizza.setBacon(true);
because the Pizza instance is not declared as a variable that is shared (instance or static field) but it is declared and used in a more restricted scope (probably a method but it could be also a initializer block).
The builder pattern provides a way to build an immutable and so by definition a thread safe object.
For example by using a builder to create a Pizza :
Pizza pizza = new Pizza.Builder().cheese(true).pepperoni(true).bacon(true).build();
Only the call to build() creates and returns the Pizza object.
Previous calls manipulate a Builder object and return a Builder.
So, if the object is immutable, you don't need to worry about synchronizing these calls :
pizza.setCheese(true);
pizza.setPepperoni(true);
pizza.setBacon(true);
as these method don't need to be provided. So they cannot be called.
About how to have thread safe JavaBeans
If you are in a context where the Pizza instance could be shared among multiple threads, these calls should be done in a synchronized way :
pizza.setCheese(true);
pizza.setPepperoni(true);
pizza.setBacon(true);
These could be declared as synchronized method and or Pizza fields could be volatile but these could not be enough.
Indeed, if a Pizza should change its state according to its own state or even according to another object, we should also synchronize the whole logic : do the checks until the state modification of the Pizza.
For example suppose the Pizza has to add some units of Pepperoni only one time :
The code could be :
if (pizza.isWaitForPepperoni()){
pizza.addPepperoni(5);
}
These statements are not atomic and so no thread safe.
pizza.addPepperoni(5); could be called by two concurrent threads even if the one of the threads already invoked pizza.addPepperoni(5);.
So we should ensure that no other thread calls pizza.addPepperoni(5) while it should not (The pizza will have too much Pepperoni) .
For example by doing a synchronized statement on the Pizza instance :
synchronized(pizza){
if (pizza.isWaitForPepperoni()){
pizza.addPepperoni(5);
}
}

Can we create a Singleton class by having non-private instanceName?

Generally, I have seen instance variables in a Singleton class being kept private. But is it possible to keep it non-private?
What if we declare an instance like this:-
final static SingletonClass singletonInstance= new SingletonClass();
Will it cause any problem for the class being a valid Singleton class?
The singleton pattern ensures that is a single instance of that class in the system at any given time. The pattern is not saying anything about public/private
Implementations can vary as long as you have one single instance available.
In your case if all constructors are private and the rest of the classes will get access to the singleton like this SingletonClass.singletonInstance the singleton pattern will be satisfied.
We make instance variable private because we want full control on it (In your case you are making it final and static, so before any one can use, it has value and later it can't be changed).
But there are few points against it:
1) If variable is private and not static, Usual singleton design will not initialize variable until somewhere we want to use it (Lazy loading).
2) We should minimize scope of variable/function as much as we can. If you don't want anyone to change it directly then do not expose it (better design)
Only plus point I can see is you do not have to worry about thread safety (In usual singleton you have to take care about it if you have multi threaded application)
The only visible difference depends on how the JVM handles itself.
Doing so, it is possible that the class is allocated before it is accessed.. this may not be true now, or ever, but this creates a dependency on the language implementation, whereas the classic approach leaves initialization in the hands of the first caller.
EDIT1:
Technically, it will still be a valid Singleton class, provided that the JVM ensures thread safety in such an access scenario. I would generaly avoid this approach since you have no way of synchronizing the creation in case it is necessary, which will violate the instance being a singleton.

What does the phrase "class object" refer to in the context of thread synchronization?

I'm new to Java and is trying to learn the concept of synchronisation. I saw this quote from Java Tutorial Oracle. I am struggling to understand what they are referring to by the phrase "Class object". What exactly is a class object?
You might wonder what happens when a static synchronized method is
invoked, since a static method is associated with a class, not an
object. In this case, the thread acquires the intrinsic lock for the
Class object associated with the class. Thus access to class's static
fields is controlled by a lock that's distinct from the lock for any
instance of the class.
Class<T> is a class itself. You can get class instances by:
Calling e.g. String.class (if you know the class statically), which is an instance of Class<String>
Calling someInstance.getClass() (if you want the concrete class of an instance), which is an instance of Class<? extends SomeInstance>, assuming that someInstance is a reference of type SomeInstance (the bound comes because it might be a subclass of SomeInstance).
Class is an actual class in Java. There exist objects of type Class. With each keyword-class will be associated one object of type Class (at least I assume - this makes sense and makes that block make sense).
I think the behavior makes sense - when you synchronize a static method, you certainly can't synchronize with respect to any object.
Arguably synchronized static is an antipattern. It's a program-wide bottleneck and anathema to scaleability. Say your program works well on a 1 GB server. If you want to adapt it to an 8 GB server with 256x the ports and network capacity and 8x the cores, there's no way to scale up the synchronized static code. You can't create another object, of course. I think the only solution is to spin up another process and another JVM with it.

Threads and synchronisation

I've problem understanding the following piece of code:-
public class SoCalledSigleton{
private final static boolean allDataLoaded = SoCalledSigleton();
private SoCalledSigleton(){
loadDataFromDB();
loadDataFromFile();
loadDataAgainFromDB();
}
}
Is this piece of code thread safe? If not then Why?
This will create an error in Java.
private final static boolean allDataLoaded = SoCalledSigleton();
You're assigning an object to a boolean variable.
You forgot to add new to instantiate the variable.
But if your code is like this
public class SoCalledSigleton{
private final static SoCalledSigleton allDataLoaded = new SoCalledSigleton();
private SoCalledSigleton(){
loadDataFromDB();
loadDataFromFile();
loadDataAgainFromDB();
}
}
It is thread-safe as static initialization and static attributes are thread-safe. They are initialized only once and exists throughout the whole life-cycle of the system.
The code is unusable in its current form, so any notions of thread safety are irrelevent.
What public interface would users use to get an instance of the singleton?
(I assume that allDataLoaded is meant to be a SoCalledSigleton and boolean is just a typo :-)
If the class has no other constructors, or the loadData* methods don't do funny business (such as publishing this), its initialization is thread safe, because the initialization of final static data members is guarded by the JVM. Such members are initialized by the class loader when the class is first loaded. During this, there is a lock on the class so the initialization process is thread safe even if multiple threads try to access the class in parallel. So the constructor of the class is guaranteed to be called only once (per classloader - thanks Visage for the clarification :-).
Note that since you don't show us the rest of the class (I suppose it should have at least a static getInstance method, and probably further nonstatic members), we can't say anything about whether the whole implementation of the class is thread safe or not.
From what we can see, there are no specific issues - it's guaranteed that the constructor will only ever by called once (so by definition can't be run multithreaded), which I presume is what you were concerned about.
However, there are still possible areas for problems. Firstly, if the loadData... methods are public, then they can be called by anyone at any time, and quite possibly could lead to concurrency errors.
Additionally, these methods are presumably modifying some kind of collection somewhere. If these collections are publically accessible before the constructor returns, then you can quite easily run into concurrency issues again. This could be an issue with anything exception updating instance-specific fields (static fields may or may not exhibit this problem depending where they are defined in the file).
Depending on the way the class is used, simply writing all of the data single-threaded may not be good enough. Collection classes are not necessarily safe for multi-threaded access even if read-only, so you'll need to ensure you're using the thread-safe data structures if multiple threads might access your singleton.
There are possibly other issues too. Thread-safety isn't a simple check-list; you need to think about what bits of code/data might be accessed concurrently, and ensure that appropriate action is taken (declaring methods synchronized, using concurrent collections, etc.). Thread-safety also isn't a binary thing (i.e. there's no such thing as "thread safe" per se); it depends how many threads will be accessing the class at once, what combinations of methods are thread-safe, whether sequences of operations will continue to function as one would expect (you can make a class "thread safe" in that is doesn't crash, but certain return values are undefined if pre-empted), what monitors threads need to hold to guarantee certain invariants etc.
I guess what I'm trying to say is that you need to think about and understand how the class is used. Showing people a snapshot of half a file (which doesn't even compile), and asking them to give a yes/no answer, is not going to be beneficial. At best they'll point out some of the issues for you if there are any; at worst you'll get a false sense of confidence.
Yeah, it's thread safe. The "method" is the constructor, and it will be called when the class is loaded, i.e. exactly once.
But looking at the stuff being done, I think it's probably a lousy idea to call it from the class loader. Essentially, you'll end up doing your DB connection and stuff at the point in time when something in your code touches the SoCalledSingleton. Chances are, this will not be inside some well-defined sequence of events where, if there's an error you have catch blocks to take you to some helpful GUI message handling or whatever.
The "cleaner" way is to use a synchronized static getInstance() method, which will construct your class and call its code exactly when getInstance() is called the first time.
EDIT: As The Elite Gentleman pointed out, there's a syntax error in there. You need to say
private final static SoCalledSingleton allDataLoaded = new SoCalledSigleton();

Java: Rationale of the Object class not being declared abstract

Why wasn't the java.lang.Object class declared to be abstract ?
Surely for an Object to be useful it needs added state or behaviour, an Object class is an abstraction, and as such it should have been declared abstract ... why did they choose not to ?
An Object is useful even if it does not have any state or behaviour specific to it.
One example would be its use as a generic guard that's used for synchronization:
public class Example {
private final Object o = new Object();
public void doSomething() {
synchronized (o) {
// do possibly dangerous stuff
}
}
}
While this class is a bit simple in its implementation (it isn't evident here why it's useful to have an explicit object, you could just declare the method synchronized) there are several cases where this is really useful.
Ande, I think you are approaching this -- pun NOT intended -- with an unnecessary degree of abstraction. I think this (IMHO) unnecessary level of abstraction is what is causing the "problem" here. You are perhaps approaching this from a mathematical theoretical approach, where many of us are approaching this from a "programmer trying to solve problems" approach. I believe this difference in approach is causing the disagreements.
When programmers look at practicalities and how to actually implement something, there are a number of times when you need some totally arbitrary Object whose actual instance is totally irrelevant. It just cannot be null. The example I gave in a comment to another post is the implementation of *Set (* == Hash or Concurrent or type of choice), which is commonly done by using a backing *Map and using the Map keys as the Set. You often cannot use null as the Map value, so what is commonly done is to use a static Object instance as the value, which will be ignored and never used. However, some non-null placeholder is needed.
Another common use is with the synchronized keyword where some Object is needed to synchronize on, and you want to ensure that your synchronizing item is totally private to avoid deadlock where different classes are unintentionally synchronizing on the same lock. A very common idiom is to allocate a private final Object to use in a class as the lock. To be fair, as of Java 5 and java.util.concurrent.locks.Lock and related additions, this idiom is measurably less applicable.
Historically, it has been quite useful in Java to have Object be instantiable. You could make a good point that with small changes in design or with small API changes, this would no longer be necessary. You're probably correct in this.
And yes, the API could have provided a Placeholder class that extends Object without adding anything at all, to be used as a placeholder for the purposes described above. But -- if you're extending Object but adding nothing, what is the value in the class other than allowing Object to be abstract? Mathematically, theoretically, perhaps one could find a value, but pragmatically, what value would it add to do this?
There are times in programming where you need an object, some object, any concrete object that is not null, something that you can compare via == and/or .equals(), but you just don't need any other feature to this object. It exists only to serve as a unique identifier and otherwise does absolutely nothing. Object satisfies this role perfectly and (IMHO) very cleanly.
I would guess that this is part of the reason why Object was not declared abstract: It is directly useful for it not to be.
Does Object specify methods that classes extending it must implement in order to be useful? No, and therefor it needn't be abstract.
The concept of a class being abstract has a well defined meaning that does not apply to Object.
You can instantiate Object for synchronization locks:
Object lock = new Object();
void someMethod() {
//safe stuff
synchronized(lock) {
//some code avoiding race condition
}
}
void someOtherMethod() {
//safe code
synchronized(lock) {
//some other stuff avoiding race condition
}
}
I am not sure this is the reason, but it allows (or allowed, as there are now better ways of doing it) for an Object to be used as a lock:
Object lock = new Object();
....
synchronized(lock)
{
}
How is Object any more offensive than null?
It makes a good place marker (as good as null anyway).
Also, I don't think it would be good design to make an object abstract without an abstract method that needs to go on it.
I'm not saying null is the best thing since sliced bread--I read an article the other day by the "Inventor" discussing the cost/value of having the concept of null... (I didn't even think null was inventable! I guess someone somewhere could claim he invented zero..) just that being able to instantiate Object is no worse than being able to pass null.
You never know when you might want to use a simple Object as a placeholder. Think of it as like having a zero in a numerical system (and null doesn't work for this, since null represents the absence of data).
There should be a reason to make a class abstract. One is to prevent clients from instantiating the class and force them into using only subclasses (for whatever reasons). Another is if you wish to use it as an interface by providing abstract methods, which subclasses must implement. Probably, the designers og Java saw no such reasons, so java.lang.Object remains concrete.
As always, Guava comes to help: with http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Optional.html
Stuff here can be used to kill nulls / Object instances for "a not-null placeholder" from the code.
There are entirely seperated questions here:
why did not they make Object abstract?
how much disaster comes after if they decide to make it abstract in a future release?
I'll just throw in another reason that I've found Object to useful to instantiate on its own. I have a pool of objects I've created that has a number of slots. Those slots can contain any of a number of objects, all that inherit from an abstract class. But what do I put in the pool to represent "empty". I could use null, but for my purpose, it made more sense to insure that there was always some object in each slot. I can't instantiate the abstract class to put in there, and I wouldn't have wanted to. So I could have created a concrete subclass of my abstract class to represent "not a useful foo", but that seemed unnecessary when using an instance of Object was just as good..in fact better, as it clearly says that what's in the slot has no functionality. So when I initialize my pool, I do so by creating an Object to assign to each slot as the initial condition of the pool.
I agree that it might have made sense for the original Java crew to have defined a Placeholder object as a concrete subclass of Object, and then made Object abstract, but it doesn't rub me wrong at all that they went the way they did. I would then have used Placeholder in place of Object.

Categories

Resources