I am using this singleton class in Java and in one method, I need an object of a class which gets instantiated in Main. I am not knowing how to pass that object to this method because this code is written in the constructor of the singleton class as I need it to be executed as soon as the program starts.
Should I take out the code from the constructor and make it a standalone method which I call from Main (though I wouldn't prefer this) or is there another way?
Any ideas?
Code:
Main:
public static void main(String[] args) {
X x; // This is the object I need to pass to the singleton class
}
Singleton class:
public SomeSingletonClass {
private Queue<Y> someQueue; // Y is another class I have in my project
private SomeSingletonClass(){
someQueue.add(new Y(<some data>, <some data>, <here I need an object of X as the constructor needs it>);
}
}
I haven't added the entire code. Just a fragment where I am stuck.
You have two main options.
The first will produce howls of derision - and rightly so because it is a dark tunnel of hell.
public class X {
}
public class Y {
public Y(String s, X x) {
}
}
public class Main {
public static X x = new X();
}
public class SomeSingletonClass {
private Queue<Y> someQueue = new LinkedList<>();;
private SomeSingletonClass() {
someQueue.add(new Y("Hello", Main.x));
}
}
Here we make the X created by Main a public static so it is now, essentially, global state in parallel with your singleton.
Most readers will understand how nasty this is but it is the simplest solution and therefore often the one taken.
The second option is lazy construction.
public class BetterSingletonClass {
private BetterSingletonClass me = null;
private Queue<Y> someQueue = new LinkedList<>();
private BetterSingletonClass(X x) {
someQueue.add(new Y("Hello", x));
}
public BetterSingletonClass getInstance (X x) {
if ( me == null ) {
me = new BetterSingletonClass(x);
}
return me;
}
}
Note that I have made no effort to make this a real singleton, n'or is this thread-safe. You can search for thread safe singleton elsewhere for plenty of examples.
Related
I am making a simulator for solving problems in Java. I want to create a task where a person needs to create class A and then in class B, in the main method, create objects of class A. The problem is that I don't know how to check the number of created objects, or at least the fact that objects were created. Can I check the creation of objects? Without making changes to classes A and B ?
public class A {
//some code
}
class B {
public static void main(String[] args) {
//User will have to create an object of class A here
}
}
You can check the number of objects created in a class by keeping a static variable and increment it upon creation automatically. For example, for class A:
class A {
private static int noOfObjects = 0;
{
numOfInstances += 1;
}
//constructors and other methods
public static int getNumOfInstances() {
return numOfInstances;
}
}
Remember, static variables initialized only once, and they're shared between all instances.
I have a java code with the structure that is shown below:
public class x{
public static void main(string[] args)
{
ysample1 = new y(m)
ysample2 = new y(l)
....
}
}
public class y{
private int m_m
public y(int m)
{
m_m = m
}
public void control()
{
h h1 = new h(ysample2)
}
}
At some point when I want to call method control for ysample1 I may need to access ysample2 object.How can I define instance of class y global, so I can access ysample2 inside the control method in class y?
Does anyone know how can I fix this? Thanks.
You can't do what you want to do the way you wrote it.
I think you need to ridefine "control()" method like this:
public void control(Y ysample)
{
h h1 = new h(ysample)
}
So now you need to have an "ysample" as parameter and you can do from your main
control(ysample2);
and you will have what i understood from you question. If you need something else please comment.
For my programming class in first year engineering I have to make a D-game in Java, with only very little knowledge of Java.
In one class I am generating a random integer via
public int rbug = (int)(Math.random() * 18);
every so many ticks. I have to use this integer in another class (in the requirements for an if-loop), and apparently it needs to be static. But when I change the variable to public int static, the value doesn't change any more.
Is there an easy way to solve this problem?
Edit: part of code added:
public int rbug = (int)(Math.random() * 18);
which is used in
public void render(Graphics g){
g.drawImage(bugs.get(rbug), (int)x, (int)y, null);
And in another class:
if(Physics.Collision(this, game.eb, i, BadBug.rbug)){
}
As error for BadBug.rbug I get the message
Cannot make a static reference to a non-static field
Using static to make things easier to access is not a very good ideal for design. You would want to make variables have a "getter" to access them from another class' instance, and possibly even a "setter". An example of this:
public class Test {
String sample = 1337;
public Test(int value) {
this.sample = value;
}
public Test(){}
public int getSample() {
return this.sample;
}
public void setSample(int setter) {
this.sample = setter;
}
}
An example of how these are used:
Test example = new Test();
System.out.println(example.getSample()); // Prints: 1337
example = new Test(-1);
System.out.println(example.getSample()); // Prints: -1
example.setSample(12345);
System.out.println(example.getSample()); // Prints: 12345
Now you might be thinking "How do I get a string from the class that made the instance variable within the class?". That's simple as well, when you construct a class, you can pass a value of the class instance itself to the constructor of the class:
public class Project {
private TestTwo example;
public void onEnable() {
this.example = new TestTwo(this);
this.example.printFromProject();
}
public int getSample() {
return 1337;
}
}
public class TestTwo {
private final Project project;
public TestTwo(Project project) {
this.project = project;
}
public void printFromProject() {
System.out.println(this.project.getSample());
}
}
This allows you to keep single instances of classes by passing around your main class instance.
To answer the question about the "static accessor", that can also be done like this:
public class Test {
public static int someGlobal = /* default value */;
}
Which allows setting and getting values through Test.someGlobal. Note however that I would still say that this is a horrible practice.
Do you want to get a new number every time that you want BadBug.rbug? Then convert it from a variable to a method.
In my work I stumbled upon such a design issue:
I need one instance of a Manager class per thread
These instances should be globally accessible, like in the singleton pattern via a static function
Each thread might need to initialize its instance with different arguments
The lifetime of these instances should be controllable, sometimes it would be beneficiary to remove an instance and allow GC to collect it
The first two points would make it a 'per thread singleton' if such a thing exists.
This is what I came up with (the code is simplified, I've omitted safety checks and so on):
public class Manager {
private final static ThreadLocal<Manager> local = new ThreadLocal<Manager>();
private int x;
Manager(int argument) { x = argument; }
public static void start(int argument) { local.set(new Manager(argument); }
public static void clean() { local.remove(); }
private void doSomething1() { x++; .... }
private int doSomething2() { if (--x == 0) clean(); ... }
public static void function1() { local.get().doSomething1(); }
public static int function2() { return local.get().doSomething2(); }
}
As you can see the clean function can be also called from within the private methods.
Also notice that through the use of static functions the reference to the instance is never leaked, so instances assigned to different threads won't get mixed.
This works quite ok, but then I got another requirement:
Different threads may need to utilize different implementations of Manager class
So I defined an interface:
public interface ManagerHandler {
void method1();
int method2();
}
And modified the Manager class:
public class Manager {
private final static ThreadLocal<ManagerHandler> local = new ThreadLocal<ManagerHandler>();
public static void start(int argument) {
ManagerHandler handler;
// depending on the context initialize handler to whatever class it is necessary
local.set(handler);
}
public static void clean() { local.remove(); }
public static void function1() { local.get().method1(); }
public static int function2() { return local.get().method2(); }
}
An example implementation would look like this:
public class ExampleManagerImplementation implements ManagerHandler {
private int x;
public ExampleManagerImplementation(int argument) { x = argument; }
public void method1() { x++; .... }
public int method2() { if (--x == 0) Manager.clean(); ... }
}
Manager class works here as a facade, forwarding all the calls to the appropriate handler. There is one big issue with this approach: I need to define all the functions both in the Manager class and in the ManagerHandler interface. Unfurtunately Manager class can't implement ManagerHandler interface, because it has static functions rather than methods.
The question is: can you think of a better/easier way to accomplish all the goals I've listed above that would be free of this issue?
There is not much you can do, as you basically need to proxy interface methods through static methods. I could only think of two ways to achieve the same functionality differently:
If you're using a DI framework, you can get rid of the static Manager and use an injected implementation of ManagerHandler which will contain the ThreadLocal.
Generate (as in 'bytecode generation') the static ManagerAccess class using the methods found in the ManagerHandler interface.
Personally, I wouldn't think of having the static ManagerAccess class (which contains the ThreadLocal) around as a serious design issue. At least as long as it keeps to its own set of responsibilities (accessing thread-scoped instances and proxying calls) and doesn't venture anywhere else.
If you're going with this design, is it necessary for Manager to totally hide ManagerHandler interface, or could you expose it so you don't have to delegate every method?
class Manager {
public static ManagerHandler getHandler() { return local.get(); }
}
The trick for creating a singleton per thread class is to use ThreadStatic attribute on your private static _current field which makes it scoped by thread. In this way, the _current field will be stored inside thread memory which is not accessible for the other threads and not shared memory of AppDomain. So, it will be available only in the scope of the thread. On the other hand, the Current property is accessible across all threads in that AppDomain but when it is called it will return the correct instance for that thread. Here is the code that you need:
public sealed class Manager
{
// As you are using the ThreadStatic here you cannot
// call the static constructor or use the Lazy implimentation for
// thread-safty and you have to use the old fashin Lock and anti-pattern.
private static readonly object _criticalArea = new object();
[ThreadStatic]
private static Manager _current;
public static Manager Current
{
get
{
if (_current == null)
{
lock (_criticalArea)
{
if (_current == null)
{
_current = new Manager();
}
}
}
return _current;
}
}
private Manager()
{
}
public string WhatThreadIsThis { get; set; }
}
[TestClass]
public class SingeltonPerThreadTest
{
private readonly EventWaitHandle _threadHandler = new EventWaitHandle(false, EventResetMode.AutoReset);
private string _sharedMemory = "I am the shared memory and yet in main thread :(";
[TestMethod]
public void TestSingeltonPerThread()
{
// Creates a _current for main thread.
Manager.Current.WhatThreadIsThis = "I am the main thread :)";
// Start another thread.
(new Thread(CallTheThreadBaseSingelton)).Start();
// Wait for it to be finished.
_threadHandler.WaitOne();
Assert.AreEqual("I am the main thread :)", Manager.Current.WhatThreadIsThis, "I am not the main thread :( ");
Assert.AreEqual("I am the other thread ;)", _sharedMemory, _sharedMemory);
}
private void CallTheThreadBaseSingelton()
{
// Creates a _current for this thread (this thread is the other one :)) ).
Manager.Current.WhatThreadIsThis = "I am the other thread ;)";
_sharedMemory = Manager.Current.WhatThreadIsThis;
_threadHandler.Set();
}
}
Cheers.
I am running a service A which has a class X. I am going to deploy another service B on same machine which is using this class X. How can I make sure that the same instance of service A is reused instead of another.
PS:Service written in JAVA.
Adding: Both these services are Axis2 services. Service B is hot-deployed. Service B used class Y which is extension of class X.
Could we try to distinguish classes, objects and services.
You have something like this?
#javax.jws.WebService
public class ServiceAAA{
public String echo(String arg) {
// some really nice code here
}
}
and you want to add
#javax.jws.WebService
public class ServiceBBB{
public String superEcho(String arg) {
// even more code here
// which needs to reuse the code from A's echo()
}
}
So clearly we don't want to cut and paste between the two implementations. How do we reuse?
Alternative 1:
Directly call A from B. You are asking how to do that. It could be done. You would just code a JAX-WS client call in your implmentation. However I stringly recommend against this. A service call is likely to be more expensive than a simple Java call.
Only do this if y6ou don't have the option of deploying the two service classes together.
Alternative 2:
Refactor the implementation. Just move the code into a worker class.
#javax.jws.WebService
public class ServiceAAA{
MyWorker worker = new Worker();
public String echo(String arg) {
return worker.doSomething(arg) ;
}
}
#javax.jws.WebService
public class ServiceBBB{
MyWorker worker = new Worker();
public String superEcho(String arg) {
worker.doSomething(arg) ;
// and some morestuff
}
}
Don't know java, but you could make use of a singleton pattern on the objects your are trying to use.
edit: I think you should have class X implementing the singleton pattern...
I understand that A uses an object of class X, and B too.
Configure your two webServices A and B to use the same instance of object X.
This configuration could be done by several means, for example:
in your starting sequence, create an instance X and assign it via setX(x) to each webService.
or you could do this in a Constructor, using static fields
Example:
#javax.jws.WebService
public class A implements WebService {
public static final X x = new X();
public void methodA() {
// use x
}
}
#javax.jws.WebService
public class B implements WebService {
private Y y = new Y(A.x);
public void methodB() {
// use y that uses x.
y.methodY();
}
}
public class Y {
private final X x;
public Y(X x) {
this.x = x;
}
public void methodY() {
// use x, it is the same instance as in A
}
}