java separate file for global variables - java

I have a newbie question. If I have some global variables that are shared by two classes or more how can I have them in a separate file so that any class can read and update them. Is this possible without using Interfaces?

Yes, since interfaces variables are all implicitly static, so each of these variables has only one instance in the jvm.
However, a better way to do it [in my opinion] would probably be having them declared in some singleton class and using it.

The best way to do this is to have your shared application state accessible via interface methods, then have an implementing class that holds the variables, and pass this instance of the class to your other classes during construction (which they accept as an instance of the interface).
This is better than using a static class or singleton since it allows you to mock out the functionality of the shared state for testing, improves general code reusability, and allows you to change the implementation and configuration of the shared state without impacting any of the code using it.
E.g.
// Session interface for all application shared state.
public interface ApplicationSession
{
public int getMaxUserLimit();
}
// A backing for the interface (simple in memory version, maybe future versions use a database, who knows).
public class SomeApplicationSession implements ApplicationSession
{
private volatile int maxUserLimit = 0;
public void setMaxUserLimit(int limit) { this.maxUserLimit = limit; }
public int getMaxUserLimit() { return maxUserLimit; }
}
// ClassA uses the supplied session.
public class MyClassA
{
private ApplicationSession session;
public myClassA(ApplicationSession session)
{
this.session = session;
}
}
// usage...
public class MyMain
{
public static void main(String[] args)
{
// Create / get session (ultimately possibly from a factory).
ApplicationSession session = new SomeApplicationSession();
ClassA myClassA = new ClassA(session);
// do stuff..
}
}

Related

Java Spring Boot Local Scope Variable make it shared

Hi I am using Sprint boot and creating microservices. I have a scenario where an object will be created and it will be used by other methods of the same class and methods of other classes. But scope will be only when this method gets called.
Class SharedObject {
private String name;
//getters setters
}
#Service
Class FirstServiceImpl {
#Autowired
SecondServiceImpl second;
public void process() {
SharedObject obj = new SharedObject();
//...
process2(obj);
}
private void process2(SharedObject obj) {
//...
second.process(obj);
}
}
#Service
Class SecondServiceImpl {
public void process(SharedObject obj) {
//...
}
}
Here SharedObject needs to be created in process method of FirstServiceImpl class and that needs to be accessed in rest of the places. But next call of process method of FirstServiceImpl class, it should create a new object. Considering this, I can pass to all the methods it requires. But any other cleaner way to achieve this ?
You can use ThreadLocal (https://docs.oracle.com/javase/8/docs/api/java/lang/ThreadLocal.html) for this use case. But use it with care, it can easily cause memory leaks if not done properly.
There are some interesting articles to read on ThreadLocal.
https://dzone.com/articles/an-alternative-approach-to-threadlocal-using-sprin-1 - Better implementation of ThreadLocal
https://plumbr.io/blog/locked-threads/how-to-shoot-yourself-in-foot-with-threadlocals
]https://javarevisited.blogspot.com/2013/01/threadlocal-memory-leak-in-java-web.html#axzz7iil9FiAC

How to make sure that there is just one instance of class in JVM?

I am developing a design pattern, and I want to make sure that here is just one instance of a class in Java Virtual Machine, to funnel all requests for some resource through a single point, but I don't know if it is possible.
I can only think of a way to count instances of a class and destroy all instance after first is created.
Is this a right approach? If not, is there any other way?
Use the singleton pattern. The easiest implementation consists of a private constructor and a field to hold its result, and a static accessor method with a name like getInstance().
The private field can be assigned from within a static initializer block or, more simply, using an initializer. The getInstance() method (which must be public) then simply returns this instance,
public class Singleton {
private static Singleton instance;
/**
* A private Constructor prevents any other class from
* instantiating.
*/
private Singleton() {
// nothing to do this time
}
/**
* The Static initializer constructs the instance at class
* loading time; this is to simulate a more involved
* construction process (it it were really simple, you'd just
* use an initializer)
*/
static {
instance = new Singleton();
}
/** Static 'instance' method */
public static Singleton getInstance() {
return instance;
}
// other methods protected by singleton-ness would be here...
/** A simple demo method */
public String demoMethod() {
return "demo";
}
}
Note that the method of using “lazy evaluation” in the getInstance() method (which
is advocated in Design Patterns), is not necessary in Java because Java already uses “lazy
loading.” Your singleton class will probably not get loaded unless its getInstance()
is called, so there is no point in trying to defer the singleton construction until it’s needed
by having getInstance() test the singleton variable for null and creating the singleton
there.
Using this class is equally simple: simply get and retain the reference, and invoke methods on it:
public class SingletonDemo {
public static void main(String[] args) {
Singleton tmp = Singleton.getInstance();
tmp.demoMethod();
}
}
Some commentators believe that a singleton should also provide a public final
clone() method that just throws an exception, to avoid subclasses that “cheat” and
clone() the singleton. However, it is clear that a class with only a private constructor
cannot be subclassed, so this paranoia does not appear to be necessary.
That's the well known Singleton pattern: you can implement this as follows:
public class SingletonClass {
//this field contains the single instance every initialized.
private static final instance = new SingletonClass();
//constructor *must* be private, otherwise other classes can make an instance as well
private SingletonClass () {
//initialize
}
//this is the method to obtain the single instance
public static SingletonClass getInstance () {
return instance;
}
}
You then call for the instance (like you would constructing a non-singleton) with:
SingletonClass.getInstance();
But in literature, a Singleton is in general considered to be a bad design idea. Of course this always somewhat depends on the situation, but most programmers advice against it. Only saying it, don't shoot on the messenger...
There is a school of thought that considers the Singleton pattern to in fact be an anti-pattern.
Considering a class A that you only wish to have one of, then an alternative is to have a builder or factory class that itself limits the creation of the number of objects of Class A, and that could be by a simple counter.
The advantage is that Class A no longer needs to worry about that, it concentrates on its real purpose. Every class that uses it no longer has to worry about it being a singleton either (no more getInstance() calls).
You want the Singleton pattern. There is an excellent discussion of how to implement this properly. If you do this right, there will only ever be one instance of the class.
Essentially what you are going to do is create a class, hold a single instantiated object of that class at the static level, and provide a static accessor to get it (getInstance() or similar). Make the constructor final so people can't create their own instances out of the blue. That link above has plenty of great advice on how to do this.
Use enum. In Java enum is the only true way to create a singleton. Private constructors can be still called through reflection.
See this StackOverflow question for more details:
Implementing Singleton with an Enum (in Java)
Discussion:
http://javarevisited.blogspot.com/2012/07/why-enum-singleton-are-better-in-java.html
I can only think of a way to count instances of a class and destroy all instance after first is created. Is this a right approach ? If not, is there any other way ?
The correct technical approach is to declare all of the constructors for the class as private so that instances of the class can only be created by the class itself. Then you code the class only ever create one instance.
Other Answers show some of the ways to implement this, according to the "Singleton" design pattern. However, implementing a singleton like this has some drawbacks, including making it significantly harder to write unit tests.
I prefer lazy singleton class, which overrides readResolve method.
For Serializable and Externalizable classes, the readResolve method allows a class to replace/resolve the object read from the stream before it is returned to the caller. By implementing the readResolve method, a class can directly control the types and instances of its own instances being deserialized.
Lazy singleton using /Initialization-on-demand_holder_idiom:
public final class LazySingleton {
private LazySingleton() {}
public static LazySingleton getInstance() {
return LazyHolder.INSTANCE;
}
private static class LazyHolder {
private static final LazySingleton INSTANCE = new LazySingleton();
}
private Object readResolve() {
return LazyHolder.INSTANCE;
}
}
Key notes:
final keyword prohibits extension of this class by sub-classing
private constructor prohibits direct object creation with new operator in caller classes
readResolve prohibits creation of multiple instances of class during object de-serialization
For that you need to use singleton pattern, I am just posting a demo code for that that may useful for your understanding.
E.g: If I want only one object for this Connect class:
public final class Connect {
private Connect() {}
private volatile static Connect connect = null;
public static Connect getinstance() {
if(connect == null) {
synchronized (Connect.class) {
connect = new Connect();
}
}
return connect;
}
}
Here the constructor is private, so no one can use new keyword to make a new instance.
class A{
private A(){
}
public static A creator(A obj){
A ob=new A();
return ob;
}
void test(){
System.out.println("The method is called");
}
}
class Demo{
public static void main(String[] args){
A ob=null;
ob=A.creator(ob);
ob.test();
}
}

Appropriate way to pass instance of class to other classes (Java)

I have a main class which has a number of instance related methods that are often needed in other classes and I often find myself passing an instance of the main class in the constructor. I often find this goes several layers deep with classes having instances of the main class that has been copied from instance to instance which I can't imagine is good for memory usage.
Is there a way to do this without having to pass the instance in the constructor or a method or at least a way to reduce the memory that is used by the instances of the main class.
To make it clear I am not looking for static methods, it is designed to be able to have more than one instance of the main class.
Example code:
public class Main {
public Main() {
Class2 class2 = new Class2(this);
}
public void someMethod() {
//Do something
}
}
public class Class2 {
private final Main instance;
public Class2(Main instance) {
this.instance = instance;
Class3 class3 = new Class3(instance);
}
}
public class Class3 {
private final Main instance;
public Class3(Main instance) {
this.instance = instance;
instance.someMethod();
}
}
You can use Dependency Injection Design Pattern.
Dependency-Injection-Design-Pattern
Spring, Google Guice and Java EE CDI frameworks facilitate the
process of dependency injection through use of Java Reflection API and
java annotations. All we need is to annotate the field, constructor or
setter method and configure them in configuration xml files or
classes.
You could also use dependency injection to pass on the dependent attributes or objects to required classes.
One such popular framework is Google Guice.
You could make methods like someMethod() in the Main class static, or if that's not possible, make the Main class itself a singleton.
Example of the former approach:
public class Main {
public Main() {
Class2 class2 = new Class2(this);
}
public static void someMethod() {
//Do something
}
}
Now you don't have to pass an instance of Main around any more, because other classes can just call Main.someMethod() directly.

Java - make class static instead of one instance of it

Let's say i have a class, and I made only one instance of it and i don't need more than that.
Should i just make the class static ? (not the class itself but the functions and the variables).
In the example below should i make the class static if i won't make more than one instance of it ?
public class Foo {
int num1;
int num2;
public void func() {
// Something in here
}
}
public static void main(String[] args) {
Foo bar = new Foo(); //I don't need more than one instance of that class.
}
If your class has no state, say:
class NoState {
static int sum(int i1, int i2) { return i1 + i2; }
}
then it makes sense to use static methods.
If you must ensure that there is only one instance of your class, then you could use a singleton, but be careful: global state can be evil.
Not as bad as a singleton, you could use static fields/methods: it can be useful is some situations but should not be abused.
In any other situations (= most of the time), just use normal instance variables/methods.
You can use an enum to define a singleton.
public enum Foo {
INSTANCE;
int num1;
int num2;
public void func() {
// Something in here
}
}
public static void main(String[] args) {
Foo bar = Foo.INSTANCE;
}
However, this is only need if you want to enforce one instance. Otherwise, I would just use new Foo(); and call it only once, if you only need one.
You can use Singleton. However, make sure if Singleton is what is really required - sometimes singletons gets overused where simple class with static methods might suffice. There are many ways to create singleton as explained What is an efficient way to implement a singleton pattern in Java?
Note that with Java 5, enum is the preferred way to create singleton.
You say that i don't need more than that so my answer is that not make more than one and if you really like to enforce the instance that it should be only one for class then use the enum best way to implement the singleton in java
for example in datasource one really needs singleton
public enum UserActivity {
INSTANCE;
private DataSource dataSource;
private JdbcTemplate jdbcTemplate;
private UserActivity() {
this.dataSource = MysqlDb.getInstance().getDataSource();
this.jdbcTemplate = new JdbcTemplate(this.dataSource);
}
public void dostuff() {
...
}
}
and if you really need that then use it otherwise go with your current logic
A class that must be instantiated once and only once, is called a singleton. That knowledge should help you narrow down your search for information. To give you a head start:
Difference between static class and singleton pattern?
Why use a singleton instead of static methods?
Basically static methods and fields means that you don't need any instances of the class.
In you case you need 'singleton' class, you can either use enum or make it a singleton by yourself, using the specific set of rules.
It really depends on the scope of your application. If you want this object to be used as a singleton you would provide a static method to get the one and only instance of the class.
public class Foo
{
private static Foo instance ....
private Foo()
{
.....
}
public static Foo getInstance()
{
return instance;
}
}
If you plan to use a framework like spring you would just add one object to the application context.
<bean class="....Foo" id="fooInstance" scope="singleton">
....
</bean>
But maybe, you can refractor this class to hold only static methods. Then you can mark the class as final and provide a private constructor.
public final class Utils
{
private Utils(){}
public static .... doFoo(....)
{
....
}
}

ThreadLocal with Singletons

I am working on the following piece of code. Two threads requiring their own instance of a singleton. Thread Local is an obvious solution to this. However I am still facing issues running the threads with their own local copy. I have an example of the scenario in a couple of java classes.
public class Singleton1 {
private int i = 0;
private static Singleton1 instance;
private Singleton1() {
}
public static final Singleton1 getInstance() {
if (instance == null) {
instance = new Singleton1();
}
return instance;
}
public int increment() {
return i++;
}
}
public class Holder1 {
private final Singleton1 instance;
public Holder1() {
ThreadLocalSingleton1 singleton1 = new ThreadLocalSingleton1();
instance = singleton1.get();
}
public int increment() {
return instance.increment();
}
private class ThreadLocalSingleton1 extends ThreadLocal<Singleton1> {
#Override
protected Singleton1 initialValue() {
return Singleton1.getInstance();
}
}
}
public class HolderTest {
/**
* #param args
*/
public static void main(String[] args) {
HolderTest test = new HolderTest();
HolderThread thread1 = test.getHolderThread("thread1");
HolderThread thread2 = test.getHolderThread("thread2");
thread1.run();
thread2.run();
}
public HolderThread getHolderThread(String name) {
return new HolderThread(name);
}
private class HolderThread implements Runnable {
String name;
Holder1 holder1 = new Holder1();
public HolderThread(String name) {
this.name = name;
}
#Override
public void run() {
while (true) {
System.out.println(name + " " + holder1.increment());
}
}
}
When the ThreadLocal wrappers call getInstance on the Singleton classes I do not get a new instance each time? How do I make this work for my purposes?
The code above is a simple version of the actual code I am working with. I have Singleton classes which I cannot change from being singletons. I am creating a test client which needs to run as a single process but with many threads. Each of these threads needs to have its own instance of these singletons.
Your target class shall not be singleton, but you must access it just using the ThreadLocal, and creating a new instance if ThreadLocal instance is empty (doesn't hold a reference to an instance of your target object).
Another solution is to make your Target class singleton, and hold its state in ThreadLocal variables.
You seem to be painted into a corner.
On the one hand, you have an existing codebase that you need to test and that code uses (genuine, properly implemented) singleton objects. In particular, the declaration of the Singleton1() constructor as private in your examplar class Singleton1 makes it impossible to declare a subclass.
On the other hand, your testing requires you to write a client with lots of these Singleton1 instances.
On the face of it, that is impossible. There is no way to make two instances of the Singleton1 class in the JVM, and there is no way to declare a (compilable / loadable) subclass of Singleton1.
This is per design; i.e. it is what the designer of the Singleton1 class intended. (And if not, then the answer is to change Singleton1 to make it easier to test. For example, by making the Singleton1 constructor not private so that multiple instances can be created for test purposes. )
(For instance, your current attempt at implementing ThreadLocalSingleton1 fails because the Singleton1.getInstance() returns the global instance of Singleton1. No matter what you do, there is no way to create any other instance of the Singleton1 class.)
However, I can think of two workarounds for your particular use-case.
I am writing a test client which needs to run as as single java process. The test client is used for load testing will have X threads accessing a server using a core project (that I cannot change too much) which has many singletons. The singletons hold state which will be required per thread.
Here are the workarounds:
Instead of running one JVM with N instances of your test thread, run N separate JVMs each with a single test thread. Each JVM / test thread can have its own instance of Singleton.
Have each of your test threads create a new classloader, and use that classloader to dynamic load the Singleton1 class and everything with a direct or indirect static dependency on the Singleton1 type. The idea is for each classloader to load its own copy of the Singleton1 class. Since each copy will be a distinct type1, it will have its own private static Singleton1 instance variable.
Note that these workarounds do provide not "thread-local" instances of your Singleton1 class. That is both technically impossible ... and a contradiction of the definition of singleton.
In both cases you have true singleton instances, but they are instances of different Singleton1 types ... for different reasons.
1 - At runtime, the type of a class instance is conceptually a pair consisting of the fully qualified name of the class and the identity of the classloader that loaded the class. If the same bytecode file is loaded by different classloaders, then you get different runtime types.
Do you mean something like this?
private static final ThreadLocal<AtomicInteger> COUNTER = new ThreadLocal<AtomicInteger>() {
#Override
protected AtomicInteger initialValue() {
return new AtomicInteger();
}
};
public static int incrementAndGet() {
return COUNTER.get().incrementAndGet();
}
Please, take a look at the ThreadLocal working example below:
public class YourDataHolder {
private static ThreadLocal dataVariable = new ThreadLocal();
private static YourDataHolder dataHolderVar;
private YourDataHolder() { }
public void storeDataToThreadLocal (String userName) {
dataVariable.set(userName);
}
public String readDataFromThreadLocal () {
if (dataVariable.get() != null) {
return (String) dataVariable.get();
}
}
public static ServiceVersionHolder getInstance () {
if (dataHolderVar == null) {
dataHolderVar = new YourDataHolder();
}
return dataHolderVar;
}
}
Use synchronized for multithreading.
public static synchronized final Singleton getInstance() {
This way the threads will "lock" the method: only one thread will be allowed to enter the method at a time, other threads will block until the method is unlocked (the thread executing it leaves). You won't have those concurrency issues.
Also you don't need 2 singletons (which IMHO actually makes no sense and defeats the very own purpose of a singleton...).

Categories