Initializing a static Java constant from a non-thread-safe method - java

Let there be a class definition like
public static class Bootstrapper {
public static final Object DEFAULT_VALUE = getDefaultValue();
private static Object getDefaultValue() {
if (DEFAULT_VALUE == null) {
return createValue(); // Not thread safe
}
return DEFAULT_VALUE;
}
}
where the createValue() method does not reference the DEFAULT_VALUE field, is only otherwise called in the constructor of the Bootstrapper class and is not thread safe.
Is there any issue (aside from programming style) with the above code? Presumably thread safety is not a problem, given the rules for class initialization, but anything important for the programmer to be aware of?

As Augusto explains, your code is thread-safe. But it's rather convoluted. It would be functionally equivalent, slightly more efficient, and much clearer to simply do this:
public static class Bootstrapper {
private static final Object DEFAULT_VALUE = createValue();
public static Object getDefaultValue() {
return DEFAULT_VALUE;
}
}
Edit: I also just noticed that the field was public and the getter was private. That should probably be the other way around.

This is safe from a threading point of view, as the class loading is thread safe and that value will be set (so getDefaultValue()) will be called after the class is loaded, but before it leaves the class loading code.
To answer PNS comment on the original question above, if the class is loaded by 2 different classloaders you are in trouble anyway, as using the synchronized keyword on getDefaultValue() will create a lock on the class... and since you have 2 classes, each one will be fully independent. You can read this in the Java Language Specification, section 4.3.4 When Reference Types Are the Same (for JLS 8).

Related

What if the benefit of using a final instance in the classic singleton pattern (if any)?

In the below snippet, Singleton1#INSTANCE is not final, while Singleton2#INSTANCE is:
public class Singleton1 {
private static Singleton1 INSTANCE = new Singleton1();
private Singleton1() {}
public static Singleton1 getInstance() {
return INSTANCE;
}
}
public class Singleton2 {
private static final Singleton2 INSTANCE = new Singleton2();
private Singleton2() {
public static Singleton2 getInstance() {
return INSTANCE;
}
}
What is the benefit of Singleton2 over Singleton1 (if any)?
There is none, Java wise. Class initialization happens atomically, within locks. No thread will be able to see Singleton1#INSTANCE partially created.
At this point, use final to clarify (to developers) that this field should not change.
I'm fairly certain that the answer is none for performance. It could prevent a bug if someone were to try and modify the reference at some point during the maintenance cycle.
final is basically used for two purposes in java -
1) For immutability - If a field is final, then it can only be initialized only once. So, if INSTANCE is not final then you can reinitialize creating one more object but this can only be done as constructor is private. So, basically final can avoid any other bugs which can be introduced at later stage as mentioned by Elliott.
2) To ensure that object is properly constructed before publishing (it is in context of multithreading) but since we are instantiating the INSTANCE on class loading (eager loading). It will not cause any issues. It will be created long before it will be used.

Can a non-changing enum method be optimized by the JVM at runtime?

Can the JVM perform runtime optimization in the following scenario?
We've got the following situation, we have this interface:
public interface ECSResource {
default int getFor(final Entity entity) {
return ResourceRetriever.forResource(this).getFor(entity);
}
}
And a concrete implementation such as:
private static enum TestResources implements ECSResource {
TR1, TR2;
}
Would the JVM be able to figure out (at runtime) that an enum instance such as TestResources.TR1 belongs to a single ResourceRetriever like ResourceRetriever.forResource(TestResources.TR1)?
In the naive implementation every call to TestResources.TR1.getFor(...) would create a new ResourceRetriever instance.
In this case though, we know that (by code inspection) a call to ResourceRetriever.forResource(this) will call the following:
public class ResourceRetriever {
private final ECSResource resource;
ResourceRetriever(ECSResource resource) {
this.resource = resource;
}
public static ResourceRetriever forResource(ECSResource resource) {
return new ResourceRetriever(resource);
}
//lots of methods
}
Hence there is nothing that can change at runtime due to random results, rounding errors, etc.
Hence the question: Can the JVM map every enum ECSResource instance to its unique corresponding ResourceRetriever.forResource(this) instance?
Note that it is possible to do such thing by your own, via the following:
private static enum TestResources implements ECSResource {
TR1, TR2;
private static final Map<TestResources, ResourceRetriever> retrieverMapping;
static {
retrieverMapping = Arrays.stream(TestResources.values())
.collect(Collectors.toMap(res -> res, ResourceRetriever::forResource));
}
#Override
public int getFor(final Entity entity) {
return retrieverMapping.get(this).getFor(entity);
}
}
The semantics of the new keyword almost certainly prohibit what you're wanting to do. (See references both in The Java Language Specification and The Java Virtual Machine Specification.) Your forResource method is always going to return a new object. I don't know of any JVMs that would do what you're trying to do, given that there is no mechanism to determine that only one ResourceRetriever should be created for any given ECSResource. This looks like a form of memoization to me, which would be handled by the language (e.g. Groovy, which has an annotation specifically for this) and not by the runtime (JVM). If Java had reified generics, you could possibly hack such a feature with something like ResourceRetriever<? extends ECSResource> but I can't say whether that would actually work, much less whether it would be a good idea or not.

How to use a factory pattern to get the instance of my Database Client?

Below is my Interface -
public interface IDBClient {
public String read(String input);
public String write(String input);
}
This is my Implementation of the Interface -
public class DatabaseClient implements IDBClient {
#Override
public String read(String input) {
}
#Override
public String write(String input) {
}
}
Now I am thinking to write Thread Safe Singleton Factory to get the instance of DatabaseClient so that I can call read and write method accordingly.. So I wrote like this by following the Initialization On Demand Holder idiom, it is still incomplete -
public class DatabaseClientFactory {
public static DatabaseClientFactory getInstance() {
return ClientHolder.s_instance;
}
private static class ClientHolder {
}
}
And I am not sure how to get the instance of DatabaseClient correctly in my above Factory? Do I need to add another method getClient() to get the instance of DatabaseClient and then call like this -
IDBClient client = DatabaseClientFactory.getInstance().getClient();
client.read(input); // or client.write(input)
You shold use Initialization-on-demand holder idiom, implementing your factory:
public class DatabaseClientFactory {
private DatabaseClientFactory() {}
private static class LazyHolder {
private static final DatabaseClient INSTANCE = new DatabaseClient();
}
public static DatabaseClient getInstance() {
return LazyHolder.INSTANCE;
}
}
This code doesn't need synchronization because of the contract of the class loader:
the class loader loads classes when they are first accessed
all static initialization is executed before anyone can use class
class loader has its own synchronization that make previous two points guaranteed to be thread safe
Here is very a nice description of correct implementation of singleton from Joshua Bloch's (one of the Java's creators) "Effective Java" book. I would strictly recommend to read at least this chapter.
A few comments:
If you want your DatabaseClient to be singleton, you have to move your factory method to this class and make it's constructor private. Otherwise there is no guarantee, that everyone will use your factory and someone won't create the second instance of this class;
Even with such approach there is no guarantee, that someone won't use reflection to create new instance of your "singleton";
If you decide for some reason to make your DatabaseClient serializable - you'll expose another ability of getting the second instance of "singleton" and will have to apply some additional techniques to avoid this (which are also not always effective).
If you still decide to go this way - you can use one of the approaches suggested by "AgilePro" or "user987339" (with moving that logic to the DatabaseClient). I believe method, described by "user987339" is preferable as it will help to make this initialization really lazy. It's not really the case with approach described by "AgilePro" cause each call to some of the static methods of that class will initialize all static fields.
If you want to get really robust singleton - I suggest you to use enums. So your DatabaseClient will look like:
public enum DatabaseClient {
INSTANCE;
DatabaseClient() {
}
public String read(String input) {
}
public String write(String input) {
}
}
And its usage:
final DatabaseClient databaseClient = DatabaseClient.INSTANCE;
P.S. One more note related to all approaches: if you get some exception during initialization of DatabaseClient - you'll get "java.lang.ExceptionInInitializerError" which won't let you to initialize this class any longer (for all further calls to this class you'll get "java.lang.NoClassDefFoundError").
This is all you need:
public class DatabaseClientFactory {
private static final DatabaseClient mySingleton = new DatabaseClient();
public static IDBClient getInstance() {
return mySingleton;
}
}
Note the private static final member that holds the singleton instance. Declaring it final prevents you fromwriting code that might create another instance. In this case we construct as static initialization time which happens before any thread can possibly access it, but you could construct with lazy initialization at run time if you desired. In this latter case you would need to make the method synchronized, which is a bit more overhead.
I made the factory method return the interface, but it could if you wish be declared to return the concrete class instead. If your concrete class has some additional methods beyond the interface you may want to do the latter.
Access it like this
IDBClient client = DatabaseClientFactory.getInstance();
It is thread safe because the variable that holds the singleton object is initialized at static initialization time, before any thread can access it. Since it is never changed after that, there is no possibility of a race condition.
This approach is simpler than that other answer because this involves only two classes, which is all you need: the factory class and the client class. One of the other answers requires three classes. This is a very small difference, since an extra class is a very small overhead, but if you believe that code should remain as simple as possible for maintenance reasons, then using three classes when two would do is a waste.

Singleton or static class?

I have the following class :
public class EnteredValues {
private HashMap<String, String> mEnteredValues;
public boolean change = false;
public boolean submit = false;
private static final EnteredValues instance = new EnteredValues();
// Singleton
private EnteredValues() {
mEnteredValues = new HashMap<String, String>();
}
public static EnteredValues getInstance() {
return instance;
}
public void addValue(String id, String value) {
if (mEnteredValues.put(id, value) != null) {
// A change has happened
change = true;
}
}
public String getValueForIdentifier(String identifier) {
return mEnteredValues.get(identifier);
}
public HashMap<String, String> getEnteredValues() {
return mEnteredValues;
}
public void clean() {
mEnteredValues.clear();
change = false;
submit = false;
}
}
This class is used to manage the values that a user has already entered, and the class should be accessible to all classes across the application.
When the activity changes I 'reset' the singleton by calling the clear method.
I chose the singleton pattern without really considering the option of a static class.
But now I was wondering if I shouldn't just use a static class..
What is the common way to handle a class that just manages values?
Is a static class faster as a singleton?
thx
The very fact that you are providing a clear method to reset the state of your Singleton dictates that you should not use Singleton. This is risky behavior as the state is global. This also means that unit testing is going to be a big pain.
One more thing. Never ever declare instance variables as public. Declare them as private or protected and provide getters and setters. Also, there is no need to initialize instance variables with a value that is their default value.
The main difference between a static class and the singleton pattern is that singleton may be used if you need to implement an interface or such. For this particular case I think you might be better off with a static class since you are not implementing any interface. Relating your question if its one faster to the other, I'd say is negligible the difference but using a static class will remove a small overhead of dynamic instantiation of the class.
What is bad in using singleton if you need such a design? If you need exactly one instance of some object designed to do specified things singleton is not a bad choice for sure.
#see Are Java static calls more or less expensive than non-static calls?
Read
http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html
From there:
Note: A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.
Just for style
I prefer not to rely on Singleton if I don't need to. Why? Less cohesion. If it's a property you can set from outside, then you can test your Activity (or whatever) with unit testing. You can change your mind to use diferent instances if you like, and so on.
My humble advise is to have a property in each of your Activities (maybe you can define a common base class?), and set it at activity initialization with a new fresh instance.
Your code will not know nothing about how to get it (except the init code and maybe you can change it in the future).
But as I've said... just a matter of taste! :)

How can I know whether an instance of a class already exists in memory?

How can I know whether an instance of a class already exists in memory?
My problem is that don't want read method if exist instance of Class
this is my code
private void jButton (java.awt.event.ActionEvent evt) {
PNLSpcMaster pnlSpc = new PNLSpcMaster();
jtabbedPanel.addTab("reg",pnlSpc);
}
I want check instance of PNLSpcMaster of course I can check by static boolean but I think this way is better.
If you want to have only one instance of "PNLSpcMaster" then you do need a singleton:
This is the common singleton idiom:
public class PNLSpcMaster {
/**
* This class attribute will be the only "instance" of this class
* It is private so none can reach it directly.
* And is "static" so it does not need "instances"
*/
private static PNLSpcMaster instance;
/**
* Constructor make private, to enforce the non-instantiation of the
* class. So an invocation to: new PNLSpcMaster() outside of this class
* won't be allowed.
*/
private PNLSpcMaster(){} // avoid instantiation.
/**
* This class method returns the "only" instance available for this class
* If the instance is still null, it gets instantiated.
* Being a class method you can call it from anywhere and it will
* always return the same instance.
*/
public static PNLSpcMaster getInstance() {
if( instance == null ) {
instance = new PNLSpcMaster();
}
return instance;
}
....
}
Usage:
private void jButton (java.awt.event.ActionEvent evt) {
// You'll get the "only" instance.
PNLSpcMaster pnlSpc = PNLSpcMaster.getInstace(); //<-- getInstance()
jtabbedPanel.addTab("reg",pnlSpc);
}
Or directly:
private void jButton (java.awt.event.ActionEvent evt) {
jtabbedPanel.addTab("reg",PNLSpcMaster.getInstace());
}
For basic usages the Singleton Pattern works very well. However for more sophisticated usages it may be dangerous.
You could read more about it: Why singletons are controversial
I think you're after the singleton pattern.
Several factors would contribute to obtaining a reliable solution in Java, as opposed to C++.
The following example is unreliable, although it could provide you with a correct enough answer if you use the hasAtleastOne() method.
class Example {
private static int noOfInstances = 0;
public Example() {
noOfInstances++;
}
public static boolean hasAtleastOne() {
if(noOfInstances > 0)
return true;
else
return false;
}
protected void finalize() throws Throwable {
noOfInstances--;
}
}
The unreliability stems out of the fact that destructors are not available in Java, unlike C++. It is upto the garbage collector to release the memory consumed by an instance - the instance could still be floating in memory as an orphan since no other object references it. Hence, you never know whether an object is no longer being referenced.
Admittedly, that is theoretically different from being absent in memory at all, but you will have to wait for the finalize() method to be called before you know for sure that no such instance of the class is available. Finalizers come with a warning - they are not to be relied upon in time-critical applications, since it could be a factor of a few seconds to minutes between object orphaning and finalization; in short there is no guarantee that they could be called.
The Dispose Pattern
You could add more reliability to the solution by implementing the Dispose pattern. This also requires the client of the class to invoke the dispose method to signal that the instance is to be disposed off, so that the instance count can be reduced. Poorly written clients will make the solution unreliable.
There isn't a reasonable way to find out whether or not an instance of a particular class already exists.
If you need to know this information, create a static boolean field and set it from the constructor:
class MyClass {
private static bool instanceExists = false;
public MyClass() {
MyClass.instanceExists = true;
}
}
For classes that have a notion of identity, the Identity Map pattern applies.

Categories

Resources