Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am trying to create a static method that moves all instances to the origin, but I can't use a static method on instance variables (like xPosition and yPosition).
Would I have to loop through all of the instances, or is there a way to do this with a static method?
Thanks in advance!
To ensure that you have all the instances of your class, I would prevent allowing to create the instances directly by making the constructors private and enforcing calling a static method to create and publish the instance, something like:
public class MyClass {
/**
* Thread-safe collection used to store all existing instances
*/
private static final Collection<MyClass> INSTANCES = new ConcurrentLinkedQueue<>();
private MyClass() {}
public static MyClass newInstance() {
// Create the instance
MyClass instance = new MyClass();
// Publish the instance
INSTANCES.add(instance);
return instance;
}
public static void release(MyClass instance) {
//Un-publish my instance
INSTANCES.remove(instance);
}
public static void releaseAll(Predicate<MyClass> predicate) {
//Un-publish all instances that match with the predicate
INSTANCES.stream().filter(predicate).forEach(INSTANCES::remove);
}
public static void apply(Consumer<MyClass> consumer) {
// Execute some code for each instance
INSTANCES.stream().forEach(consumer);
}
}
Then your code will be:
// Create my instance
MyClass myClass = MyClass.newInstance();
// Execute some code here
...
// Release the instance once the work is over to prevent a memory leak
MyClass.release(myClass);
...
// Execute some code on all instances
// Here it will print all instances
MyClass.apply(System.out::println);
...
// Release all instances that match with a given test
MyClass.releaseAll(myClass -> <Some Test Here>);
You can do it with a static method if you have a static registry of all the instances.
class YourClass {
static List<YourClass> instances = new ArrayList<>();
YourClass() {
instances.add(this); // Yuk! Unsafe publication.
}
static void moveAll() {
for (YourClass instance : instances) {
// Do something to instance.
}
}
}
But I'd recommend you don't do that, but instead have a non-static registry class:
class YourClassRegistry {
List<YourClass> instances = new ArrayList<>();
void add(YourClass instance) {
instances.add(instance);
}
void moveAll() {
for (YourClass instance : instances) {
// Do something to instance.
}
}
}
Example usage:
YourClassRegistry registry = new YourClassRegistry();
registry.add(new YourClass());
registry.add(new YourClass());
registry.add(new YourClass());
registry.moveAll();
This allows you to have separate groups of "instances", that you can move separately.
Global mutable state (like the static version of the registry) is a pain in the neck, reduces testability, requires more care with respect to thread safety etc.
Related
EDIT: Adding more context and code here:
Currently this is what I have:
public class MyClass{
private static MyClass2 mySharedObject = null; //this is the object that I want to share across m
private SomeRandomClass someRandomClass;
public MyClass(MyClass3 object3, MyClass4 object4, SomeRandomClass someRandomClass){
/* it just so happens that it is guaranteed that someRandomClass, no
matter which thread creates it, will have the same value. But the value is not known in design time and hence I can't move this initialize code to the static {} block, as suggested by many folks. One thing that I can do is move the creation of this sharedObject outside MyClass and do it before any threads actually use it. Unfortunately, I am dealing with a legacy code here and didn't want to do that change and that's why asked if the approach I presented is good enough or there is something better? */
this.someRandomClass = someRandomClass;
synchronized(mySharedObject){
if(mySharedObject ! =null){
mySharedObject = new MyClass2(someRandomClass);//It doesn't matter which thread wins to create this object. I just need a valid instance of someRandomClass to create mySharedObject. Once it is created, I can use it for all the threads.
}
}
}
}
Is there a better way?
PS: I don't want to pass this shared object in the constructor of MyClass and/or I don't want to make MyClass2 as singleton.
Thanks
Use a static initializer block.
public class MyClass {
private static MyClass2 mySharedObject;
static {
mySharedObject = null; // whatever value here
}
// The rest of MyClass
}
EDIT: From your comments, another approach is that you set the value of mySharedObject externally before you begin whatever concurrent process you are attempting:
/* MyClass.java */
public class MyClass {
private static MyClass2 mySharedObject = null;
public static SetSharedObject(MyClass2 sharedObject) {
mySharedObject = sharedObject;
}
// The rest of the class
}
/* Elsewhere.java */
MyClass2 sharedObject = new MyClass2(someRandomClass);
MyClass.SetSharedObject(sharedObject);
// Do whatever you do with MyClass concurrency
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
So I'm new to java, but I'm fluent in python, and I'm stuck on a basic problem. Do I have to declare an object in the same method in which I'm going to use it? Or is there a way to transfer objects from method to method? Thank you for your help (:
Transfer objects from method to method is generally the most recommended way. This helps keep code modular and reduces coupling. A common concept in Java is getters and setters for custom classes. See example below:
public class MyClass {
private String myString; // this variable can only be directly access from within MyClass scope.
// constructor - called when an instance of MyClass is initialized ( e.g. MyClass myClass = new MyClass(); )
public MyClass(){
myString = "Hello world!"; // init my_string
}
// Can access variable from within class to print
public void printMyString(){
System.out.println(myString);
}
// Can set private class variables
public void setMyString(String input){
this.myString = input; // set value
}
// Can get (return) private class variables
public String getMyString(){
return myString; // get value
}
}
From another section in your program:
MyClass myClass = new MyClass(); // init class (calls constructor)
System.out.println(myClass.getMyString()); // prints "Hello world!"
myClass.setMyString("Hola"); // changes value of myString
System.out.println(myClass.getMyString()); // prints "Hola"
System.out.println(myClass.myString); // Error: cannot directly access private variable of java class MyClass.
Variables which should be available across multiple methods should be declared at the top of the class as follows.
public class Test{
int number = 1;
String text = "hello";
public int method1() {
return number + 1;
}
public String method2() {
return text + " moo";
}
}
Alternatively, if you have another variable with the same name as one of the global variables you can refer to the global one with something like this.number
I have an object say A that loads some data from disk and it takes a bit long time to load. Many of other objects need its methods and data so I don't want neither any time I need it create a new one nor passing it through class constructor. Is there any way to create an instance of the class A only once at the beginning of the running project and all the other objects have access to the object A?
I apologize if my question is duplicated but I don't have any idea about what keywords relate to this question to find related questions.
In that case you are dealing with the Singleton Design Pattern you should declare youre class like this:
public class SingleObject {
//create an object of SingleObject
private static SingleObject instance = new SingleObject();
//make the constructor private so that this class cannot be
//instantiated
private SingleObject(){}
//Get the only object available
public static SingleObject getInstance(){
return instance;
}
public void showMessage(){
System.out.println("Hello World!");
}
}
And then you can use it as intended.
In fact the approach here is to use static members like this:
public class Vehicle {
private static String vehicleType;
public static String getVehicleType(){
return vehicleType;
}
}
The static modifier allows us to access the variable vehicleType and the method getVehicleType() using the class name itself, as follows:
Vehicle.vehicleType
Vehicle.getVehicleType()
Take a look at Java static class Example for further information.
Sure. The design pattern is called a singleton. It could look like this:
public class Singleton {
private static Singleton instance;
private Singleton () {}
/*
* Returns the single object instance to every
* caller. This is how you can access the singleton
* object in your whole application
*/
public static Singleton getInstance () {
if (Singleton.instance == null) {
Singleton.instance = new Singleton();
}
return Singleton.instance;
}
}
All objects can use the singleton by calling Singleton.getInstance()
Need to create specified number of instance for a particular class in JVM
Like for Singleton pattern, we manage and create only 1 instance.
now for suppose class Abc, i just want to
1.) create only 3 instances at maximum.
2.) Multithreading environment.
class Abc{
private static Abc abc1;
private static Abc abc2;
private static Abc abc3;
private Abc(){
}
public static synchronized Abc getInstance1(){
if(abc1 == null){
abc1 = new Abc();
}
return abc1;
}
: // same as above for abc2
: // same as above for abc3
}
** Now problem is suppose i want to increase instance from total 3 to to say 4 or 5 or n number.
Also i do want to expose so many methods (getInstance1(), getInstance2()... etc)
It looks like you want an instance per thread.
There or out of the box solutions for this, the DI containers like Guice, spring and many other.
If you really want to do this yourself, you could use a map the keep an instance per thread.
public class Abc {
private static Map<Long, Abc> instances = new HashMap<Long, Abc>();
//hiding the constructor
private Abc() { }
public static Abc getInstance() {
Long threadId = Thread.currentThread().getId();
if (!instances.containsKey(threadId)) {
instances.put(threadId, new Abc());
}
return instances.get(threadId);
}
}
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I've been using several methods of calling methods. More recently, I've been using a static instance of a class, I do believe that's the proper term for it (please correct me if I'm wrong). Which is better (or even suggest ideas), and why?
The first way I was the simple old static methods.
static void exampleMethod1(){}
static void exampleMethod2(){}
The second way (someone said this is an improvement).
public class ExampleClass{
public static ExampleClass instance;
public ExampleClass(){
instance = this;
}
public static ExampleClass getInstance(){
return instance;
}
void exampleMethod1(){
//code
}
void exampleMethod2(){
//code
}
// To call the method I simply getInstance().exampleMethod1
}
The term you're looking for is singleton.
Both static methods and instance methods on a singleton are okay approaches, but note that the static methods approach cannot implement an interface, so if you need to implement an interface, use a singleton.
For example:
public enum HelloWorld implements Runnable {
INSTANCE;
#Override
public void run() {
System.out.println("Hello, world!");
}
}
// ...
new Thread(HelloWorld.INSTANCE).start();
If your hello-world code were in a static method, it wouldn't have been able to directly implement the Runnable interface.
If all the methods are static, and you don't need initializing the class or have class members then just make a static utility class.
A static class with only static functions is just fine.
As chris answered above me, it sounds like you are looking for a singleton, which you should use only if you do have non static aspects to your class, but you want to limit the number of instances of it.
public static class GeneralFunctions
{
public static class ArrayFunctions
{
public static void OnArray{};
}
public static class PrintingFunctions
{
public static void PrintBuffer(byte[] buffer){};
public static void PrintQword(ulong qword){};
}
}
You can have a class with only static methods, and the methods can (if needed) use static fields in the class for their persistent data. Or you can use a "singleton" class instance to do roughly the same thing with instance methods and instance fields.
In general, if you have a class that consists only of methods that have no state (eg, the Math class), you should make the methods static and not have/allow an instance. If the methods must have some shared state, however, it's probably wiser to have some sort of "singleton" implementation.
To make a proper singleton you must make the constructor private. The static final declaration ensures that instance will be initialized when the class is first loaded. This is the simplest way to create singletons in Java, but note that there are other ways.
public class ExampleClass
{
private final static ExampleClass instance = new ExampleClass();
private ExampleClass()
{
// prevents instantiation
}
public static ExampleClass getInstance()
{
return instance;
}
void exampleMethod1()
{
//code
}
void exampleMethod2()
{
//code
}
}
To get an instance of the class:
ExampleClass exampleClass = ExampleClass.getInstance();
exampleClass.exampleMethod1();