I would like to encapsulate my fields (variables), into a different file. Like getting out the logic of my application into a different file (logic.java ?), where every class could access the variables that should be "global".
Netbeans is capable of doing encapsulation, but it will just put a list of setter/getter functions into the same file.
(Later, I would like to call the functions with Logic lo = new Logic();, and lo.getValue(), for example.)
If there is a better way of doing this, please enlighten me, and I'll delete the question. (The classes are in different package. app.logic; app.desk; app.net, etc.)
What you want here are advanced refactoring capabilities, and for that I'd suggest you take a look at IntelliJ IDEA (The community edition is free to use and download and is available for all platforms).
Take a look at it here.
I don't know if I understand correctly but what you can do is implement a singleton class:
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton() {
}
public static Singleton getInstance() {
return instance;
}
// members, getters and setters
}
Now this guarantees that you only have one instance of Singleton in your entire application that can be obtained anywhere with Singleton.getInstance().
Related
What is the standard approach/best practice to creating variables that are program- or package-wide in Java?
I want to set up some global variables that are accessible by multiple classes. Examples of these global variables would be things like a boolean flag testModeOn, a language setting, current local server, time display format, etc. According to some other questions (namely this one) there aren't any global variables, but there are some work-arounds using interfaces (not recommended?) or classes. Since the original poster didn't explain their situation, they got nearly every answer under the sun and I want to ask specifically for program configuration variables.
Is it better to create a class/package/interface and then import it into my working class/package? Is there anything I should be aware of when trying to implement these variables using a separate class or interface? Is there any other way to fudge package-level variables since Java apparently doesn't do this natively?
NOTE: These variables would probably not change except when the program is re-compiled.
If you're talking about constants, then they should be declared as static final fields in a class (never in an interface, according to Joshua Bloch).
If you're talking about settings which can change on the fly, then these could be either static fields in a class, or you could create a ConfigHandler class to manage the setting and fetching of configurable values.
Using class fields for mutable values might lead to concurrency problems, so if your application is multi-threaded it might be better to create a ConfigHandler class which manages concurrent access carefully and provides synchronized methods to avoid problems.
In my opinion, the best approach to passing anything into your classes is using dependency injection. This would eliminate your need for Singletons, static constants and the likes.
Depending on which DI you favor, here are some link solutions to the problem you describe:
CDI
Spring
Guice
Create a Bean class if multiple variables are required to be used in different classes. Best practice is to create a private variable with its getters and setters.
public class ListBean implements Serializable
{
private boolean testModeOn;
public boolean getTestModeOn()
{
return testModeOn;
}
public setTestModeOn(boolean testModeOn)
{
this.testModeOn = testModeOn;
}
In general there are so many ways to do it wrong regarding this topic.
The simple way is to use a Singelton.
This is not an option - Singelton is an Anti-Pattern. http://c2.com/cgi/wiki?SingletonsAreEvil
So what is else there? An Interface with public static final variables?
Not an option - Thats simply not the use case of an interface: https://stackoverflow.com/a/2659740/1248724
so what is else there?
The answer is:
What I prefer is the spring boot way (e.g. Dependency Injection)
Here an code example which is obviously Spring.
import org.springframework.stereotype.*
import org.springframework.beans.factory.annotation.*
#Component
public class MyBean {
#Value("${name}")
private String name;
// ...
}
If you are using some similar Framework such things could be easy archived.
If that is somehow not possible in your environment I had to code something like this:
public final class Configuration {
private Configuration() {
// make sure there is no instance of this class
}
public static final MySetting<DateFormat> setting = new SampleProperty();
public interface MySetting<T> {
T get();
}
private static final class SampleProperty implements MySetting<DateFormat> {
#Override
public DateFormat get() {
return new SimpleDateFormat("...");
}
}
// other inner classes that implement the MySetting interface
}
public static void main(final String[] args) {
Configuration.setting.get();
}
Benefits:
- You can validate your properties how ever you want.
- You can work with the java security manager if you like to
Downsides:
- You may have to maintain a bunch of code (this should be easier with lambda expressions)
- Not that great as the way spring offers here for example.
A very similar approach I just found: https://stackoverflow.com/a/3931399/1248724
Is there any method to check whether any instance of a class is running?
I have a GUI and I don't want open another instance of it, if a one is already running.
I know about including a counter in constructor. Any method except that?
Thanks in advance!!
Use the singleton pattern.
Here is a simple implementation in java of a singleton:
public class MyClass {
private static MyClass INSTANCE = new MyClass();
private MyClass() { // private constructor prevents creation outside class
}
public static MyClass getInstance() {
return INSTANCE;
}
}
Note that this is not "bulletproof" (there are "hacks" you can use via reflection to circumvent this and create two instances), however if you're the only user of the code it will be fine.
Is there any method to check whether any instance of a class is running?
The simple answer is No.
The normal way to deal with this problem is to use the Singleton design pattern. The idea of the pattern is that you write the code to remove the possibility of creating multiple instance of the class.
In Java you typically do this by declaring the class constructor to be private, and providing access to the singleton instance via a static method. Depending on your precise requirements, the singleton can be created eagerly or lazily.
Bohemian's answer provides a good example of this approach.
(In Java 5 or later, it is also possible to use enum types to implement singletons.)
Use Enum as recommended by J. Bloch (Effective Java Programming 2nd Ed., Addison Wesley)
I have a Preference class (module) that's used across several different apps. Basically it's a cache of the preferences so that the systems don't have to call the backend all the time. It's similar to a cache but with some additional niceties such as isPreferenceSelected, has some helper methods, etc.
The issue is that I'd like to include a savePreference within the class so that whoever uses it can just override that method, be it to a database, to a flat file, etc. The key is that this module just doesn't want to care. The issue is that it's not an abstract class so I can't override the static methods and even if it was, I don't want to create a million instances because I don't want to load the preferences each time. And I can't create a abstract singleton either.
Therefore I'm not sure what to do. Here is a code snippet of what I'd like to do with comments:
// Please ignore the missing Generics, etc.
public class Preference
{
private static HashMap preferences = new HashMap();
public static ...
// Some preferences are objects, such as images, etc.
public static setPreference(String name, Object value)
{
.. some helper code
preferences.put(name, value); // ignoring issues with if it already exists ;)
savePreference(name, value); // saves to database, flatfile, etc.
}
}
That was the core class/code that the different systems leverage. Now what I'd like to do is say in a webapp, a desktop app, etc., be able to use this class in my code such as:
public someFunction(...)
{
.. do some cool code
Preference.savePreference("logoImage", image);
}
And have the savePreference() method not just save the in-memory preferences, but also save it to the external source. Otherwise everywhere I have savePreference() I have to follow it by a db call savePreferenceToDB(), a FlatFile call such as savePreferenceToFlatFile(), and so on. This is very error prone, someone somewhere will forget to save it. Plus it really makes no sense to sprinkle the save to permanent storage code everywhere with this type of code when it should really only be done once. Also remember that the main module has no idea if the permanent storage is a database, an xml file, a flat file, etc.
Hint: If I did Preference.getInstance().savePreference() that wouldn't work because you can't abstract a singleton. And I can't create a static method savePreference() because it's not possible to override a static method.
The only options I can see is to create some kind of complex Factory pattern, but that seems like a lot of overkill to me. Therefore any suggestions would be greatly appreciated.
This sounds like something that your dependency injection (DI) container should be handling, not a complex factory pattern.
That is, I think you should ditch the usages of static, have whatever creates the other applications inject an instance of Preference into your applications. You can do this without a DI framework if you just take the Preference as a parameter in your constructor for whatever other classes depend on it.
Edit: Let me give you an example of dependency injection without a framework. Take the following set of classes:
public class Preference
{
private String userName;
public Preference(String userName)
{
this.userName = userName;
}
public void savePreference()
{
// Default implementation saves it to the screen. ;-)
System.out.println(userName);
}
}
public class Foo
{
private Preference p;
public Foo(Preference p)
{
this.p = p;
}
}
public class Bar
{
private Preference p;
public Bar(Preference p)
{
this.p = p;
}
}
public class Main
{
public static void main(String[] args)
{
Preference p = new Preference("Mike");
Foo f = new Foo(p);
Bar b = new Bar(p);
}
}
This is a simplistic example, but it satisfies your requirements:
The Preference instance is only created once
The Preference class can be extended by whoever implements the Main class to instantiate whatever kind of Preference subclass they want to, if they wanted to persist it in a relational database (or whatever)
By avoiding having static calls in the first place you also make it possible for your someFunction() example to be unit tested without pulling in a potentially big, complicated preferences framework. Rather, someone implements a mock Preference subclass and passes it into the class that runs someFunction(). Your code will be much more testable that way.
#Mike says:
... I think you should ditch the usages of static
#Stephane responds:
... what is the major issue with static methods?
It is not just static methods. It is also the singleton instance.
Basically, they are inflexible:
They make it difficult to do things in alternative ways, as illustrated by your problem. If you didn't use a static method and a private singleton instance, you could create a Preferences interface and/or abstract base class, together with implementations that load and save the in-memory preferences in different ways.
Static instances tend to make testing harder. For instance, if you had a preferences UI that made use of your Preferences class, you couldn't unit test the UI classes using a "mock" version of Preferences. (Or at least, it would be a lot harder to do.)
Statics tend to make it difficult to reuse your code because of the hard dependencies on specific named classes and specific implementations.
Statics are non-OO. This is not intrinsically a bad thing, but it does mean that you can't make use of the nice properties of OO ... like overriding and polymorphism ... when you use statics.
If you have a significant number of these static methods / static objects in your application, a DI framework is a good solution. But as #Mike says, using Factory methods and passing objects in constructors will work just as well in many cases.
You commented:
One of the reasons I have it as a static class is because the preferences are loaded at startup. After that they stay in memory in the one static object. With DI, each time I create the object, I'd have to reload the information into memory from the data source. This defeats the whole purposes of having a Preferences Object (that pretty much acts like a cache with benefits).
This does not require you to use a static instance.
With DI (or explicitly wiring instances via constructors), you don't create the Preferences object more than once. You create it once, and then inject it as many times as required.
There is a halfway between your current approach with a static method that wraps a static instance of a hard-wired class and full DI. That is a what can best be described as a static holder; e.g.
public interface Preferences {
// Preferences API
}
public abstract class PreferencesBase implements Preferences {
// Implement as much if the API as makes sense
}
public class FileBackedPreferences extends PreferencesBase {
// Implement (protected) persistence methods.
}
public class DatabaseBackedPreferences extends PreferencesBase {
// Implement (protected) persistence methods.
}
public class ApplicationPreferences {
private static Preferences instance;
private ApplicationPreferences() { }
public Preferences getInstance() { return instance; }
// Call this once during application startup with the
// Preferences instance to be used by the application.
public void initPreferences(Preferences instance) {
if (this.instance != null) {
throw new IllegalStateException(...);
}
this.instance = instance;
}
}
I think it might take some rework of your design (unfortunately, I don't have a decent whiteboard in my apartment yet, so I can't easily sketch things out to conform), but I immediately thought Strategy pattern as soon as you said this:
The issue is that I'd like to include a savePreference within the class so that whoever uses it can just override that method, be it to a database, to a flat file, etc. The key is that this module just doesn't want to care.
You might have an abstract Preferences class that has every method but saving (and loading) implemented. In the sense of the pattern, this would be the Strategy interface. Your different types of saving and loading would be handled by the concrete implementations.
Create an interface for your preference manipulation class:
public interface PreferenceHandler {
void savePreference();
void readPreference();
}
Pass an instance of type PreferenceHandler to your class with all the static methods.
Invoke the methods on that class within your class.
Though, not lovin' all those static methods. It's probably why you're having so many issues here. Create a factory that gives you a copy of the class if you don't want to be creating lots of copies of it. But static methods really impede code re-use and extension. Or perhaps use a framework like Spring to manage classes of this sort.
I had an interview recently and he asked me about Singleton Design Patterns about how are they implemented and I told him that using static variables and static methods we can implement Singleton Design Patterns.
He seems to be half satisfied with the answer but I want to know
How many different ways we can
implement Singleton Design Pattern
in Java ?
What is the scope of Singleton Object and how does it actually work inside JVM ? I know we would always have one instance of Singleton Object but what is the actual scope of that object, is it in JVM or if there are multiple application running than it's scope is per context basis inside the JVM, I was really stumped at this and was unable to give satisfying explanation ?
Lastly he asked if it is possible to used Singleton Object with Clusters with explanation and is there any way to have Spring not implement Singleton Design Pattern when we make a call to Bean Factory to get the objects ?
Any inputs would be highly appreciated about Singleton and what are the main things to keep in mind while dealing with Singletons ?
Thanks.
There are a few ways to implement a Singleton pattern in Java:
// private constructor, public static instance
// usage: Blah.INSTANCE.someMethod();
public class Blah {
public static final Blah INSTANCE = new Blah();
private Blah() {
}
// public methods
}
// private constructor, public instance method
// usage: Woo.getInstance().someMethod();
public class Woo {
private static final Woo INSTANCE = new Woo();
private Woo() {
}
public static Woo getInstance() {
return INSTANCE;
}
// public methods
}
// Java5+ single element enumeration (preferred approach)
// usage: Zing.INSTANCE.someMethod();
public enum Zing {
INSTANCE;
// public methods
}
Given the examples above, you will have a single instance per classloader.
Regarding using a singleton in a cluster...I'm not sure what the definition of "using" is...is the interviewer implying that a single instance is created across the cluster? I'm not sure if that makes a whole lot of sense...?
Lastly, defining a non-singleton object in spring is done simply via the attribute singleton="false".
I disagree with #irreputable.
The scope of a Singleton is its node in the Classloader tree. Its containing classloader, and any child classloaders can see the Singleton.
It's important to understand this concept of scope, especially in the application servers which have intricate Classloader hierarchies.
For example, if you have a library in a jar file on the system classpath of an app server, and that library uses a Singleton, that Singleton is going to (likely) be the same for every "app" deployed in to the app server. That may or may not be a good thing (depends on the library).
Classloaders are, IMHO, one of the most important concepts in Java and the JVM, and Singletons play right in to that, so I think it is important for a Java programmer to "care".
I find it hard to believe that so many answers missed the best standard practice for singletons - using Enums - this will give you a singleton whose scope is the class loader which is good enough for most purposes.
public enum Singleton { ONE_AND_ONLY_ONE ; ... members and other junk ... }
As for singletons at higher levels - perhaps I am being silly - but my inclination would be to distribute the JVM itself (and restrict the class loaders). Then the enum would be adequate to the job .
Singleton is commonly implemented by having a static instance object (private SingletonType SingletonType.instance) that is lazily instantiated via a static SingletonType SingletonType.getInstance() method. There are many pitfalls to using singletons, so many, in fact, that many consider singleton to be a design anti-pattern. Given the questions about Spring, the interviewer probably was looking for an understanding not only of singletons but also their pitfalls as well as a workaround for these pitfalls known as dependency injection. You may find the video on the Google Guice page particularly helpful in understanding the pitfalls of singletons and how DI addresses this.
3: Lastly he asked if it is possible to used Singleton Object with Clusters with explanation and is there any way to have Spring not implement Singleton Design Pattern when we make a call to Bean Factory to get the objects ?
The first part of this question is hard to answer without a technological context. If the cluster platform includes the ability to make calls on remote objects as if they were local objects (e.g. as is possible with EJBs using RMI or IIOP under the hood) then yes it can be done. For example, the JVM resident singleton objects could be proxies for a cluster-wide singleton object, that was initially located / wired via JNDI or something. But cluster-wide singletons are a potential bottleneck because each call on one of the singleton proxies results in an (expensive) RPC to a single remote object.
The second part of the question is that Spring Bean Factories can be configured with different scopes. The default is for singletons (scoped at the webapp level), but they can also be session or request scoped, or an application can define its own scoping mechanism.
a static field can have multiple occurrences in one JVM - by using difference class loaders, the same class can be loaded and initialized multiple times, but each lives in isolation and JVM treat the result loaded classes as completely different classes.
I don't think a Java programmer should care, unless he's writing some frameworks. "One per VM" is a good enough answer. People often talk that way while strictly speaking they are saying "one per classloader".
Can we have one singleton per cluster? Well that's a game of concepts. I would not appreciate an interviewer word it that way.
There's the standard way, which you already covered. Also, most dependency-injection schemes have some way to mark a class as a singleton; this way, the class looks just like any other, but the framework makes sure that when you inject instances of that class, it's always the same instance.
That's where it gets hairy. For example, if the class is initialized inside a Tomcat application context, then the singleton instance's lifetime is bound to that context. But it can be hard to predict where your classes will be initialized; so it's best not to make any assumptions. If you want to absolutely make sure that there's exactly one instance per context, you should bind it as an attribute of the ServletContext. (Or let a dependency-injection framework take care of it.)
--
Not sure I understand the question - but if you're talking about having a singleton instance that's shared between several cluster nodes, then I think EJB makes this possible (by way of remote beans), though I've never tried it. No idea how Spring does it.
Singleton is a creational pattern and hence governs object instantiation. Creating singletons would mandate that you voluntarily or involuntarily give up control on creating the object and instead rely on some way of obtaining access to it.
This can be achieved using static methods or by dependency injection or using the factory pattern. The means is immaterial. In case of the normal protected constructor() approach, the consumer perforce needs to use the static method for accessing the singleton. In case of DI, the consumer voluntarily gives up control over the instantiation of the class and instead relies on a DI framework to inject the instance into itself.
As pointed out by other posters, the class loader in java would define the scope of the singleton. Singletons in clusters are usually "not single instances" but a collection of instances that exhibit similar behavior. These can be components in SOA.
The Following Code is from here
The Key point is you should Override the clone method...The Wikipedia example also is helpful.
public class SingletonObject
{
private SingletonObject()
{
// no code req'd
}
public static SingletonObject getSingletonObject()
{
if (ref == null)
// it's ok, we can call this constructor
ref = new SingletonObject();
return ref;
}
public Object clone()
throws CloneNotSupportedException
{
throw new CloneNotSupportedException();
// that'll teach 'em
}
private static SingletonObject ref;
}
Query 1:
Different ways of creating Singleton
Normal Singleton : static initialization
ENUM
Lazy Singleton : Double locking Singleton & : Initialization-on-demand_holder_idiom singleton
Have a look at below code:
public final class Singleton{
private static final Singleton instance = new Singleton();
public static Singleton getInstance(){
return instance;
}
public enum EnumSingleton {
INSTANCE;
}
public static void main(String args[]){
System.out.println("Singleton:"+Singleton.getInstance());
System.out.println("Enum.."+EnumSingleton.INSTANCE);
System.out.println("Lazy.."+LazySingleton.getInstance());
}
}
final class LazySingleton {
private LazySingleton() {}
public static LazySingleton getInstance() {
return LazyHolder.INSTANCE;
}
private static class LazyHolder {
private static final LazySingleton INSTANCE = new LazySingleton();
}
}
Related SE questions:
What is an efficient way to implement a singleton pattern in Java?
Query 2:
One Singleton instance is created per ClassLoader. If you want to avoid creation of Singleton object during Serializaiton, override below method and return same instance.
private Object readResolve() {
return instance;
}
Query 3:
To achieve a cluster level Singleton among multiple servers, store this Singleton object in a distributed caches like Terracotta, Coherence etc.
Singleton is a creational design pattern.
Intents of Singleton Design Pattern :
Ensure a class has only one instance, and provide a global point of
access to it.
Encapsulated "just-in-time initialization" or "initialization on
first use".
I'm showing three types of implementation here.
Just in time initialization (Allocates memory during the first run, even if you don't use it)
class Foo{
// Initialized in first run
private static Foo INSTANCE = new Foo();
/**
* Private constructor prevents instantiation from outside
*/
private Foo() {}
public static Foo getInstance(){
return INSTANCE;
}
}
Initialization on first use (or Lazy initialization)
class Bar{
private static Bar instance;
/**
* Private constructor prevents instantiation from outside
*/
private Bar() {}
public static Bar getInstance(){
if (instance == null){
// initialized in first call of getInstance()
instance = new Bar();
}
return instance;
}
}
This is another style of Lazy initialization but the advantage is, this solution is thread-safe without requiring special language constructs (i.e. volatile or synchronized). Read More at SourceMaking.com
class Blaa{
/**
* Private constructor prevents instantiation from outside
*/
private Blaa() {}
/**
* BlaaHolder is loaded on the first execution of Blaa.getInstance()
* or the first access to SingletonHolder.INSTANCE, not before.
*/
private static class BlaaHolder{
public static Blaa INSTANCE = new Blaa();
}
public static Blaa getInstance(){
return BlaaHolder.INSTANCE;
}
}
Assume I have a singleton class in an external lib to my application. But still I can
create instances of that particular class using reflection. Like this
Class clas = Class.forName(Private.class.getName());
for(Constructor c : clas.getDeclaredConstructors()){
c.setAccessible(true);
Private p = (Private) c.newInstance();
System.out.println(p);
}
How can I restrict this ? .
Thanks
J
By using a SecurityManager and controlling controlling ReflectPermission("suppressAccessChecks") (example).
The security manager impacts performances though, and it is rarely used on the server side.
See Hack any Java class using reflection attack and
How to set SecurityManager and Java security policy programmatically .
If you're talking about singletons in particular: that's one reason why the best way to implement them is via an enum:
public enum YourSingleton {
INSTANCE;
// methods go here
}
If you're talking about using setAccessible() in general: If the code is written by someone you don't trust not to do underhanded tricks like that, you shouldn't run it anyway (or run it in a sandbox). Among developers, public/private should be considered metainformation about how the code is intended to be used - not as a security feature.
Long story short: you can't.
Any constructor, public as well as private, can be accessed by reflection and can be used to instantiate a new object.
You will need to resort to other methods such as SecurityManager.
I don't think that you can restrict this.
It is obviously a dangerous/questionable practice to use reflection to access the private parts of others (snicker), but it is sometimes necessary by various types of tools and applications.
AFAIK this is sort of metaprogramming and therefore requires check on different layer of abstraction. From Javadoc I suppose, you should use SecurityManager to enforce the behaviour you want: setAccessible().
Generally IMHO you should really know what you are doing when you are metaprogramming and changing access should really have good reasons to be done.
You can do like this.
private static final Private INSTANCE = new Private();
private Private() {
if(INSTANCE !=null)
throw new IllegalStateException("Already instantiated");
}
public static Private getInstance() {
return INSTANCE;
}