I want to use a private int type accessCount() to return the times of Singleton has been accessed via the getInstance() method, but always get error. Here's my two piece of code:
ExampleSingleton.java
public class ExampleSingleton {
private int accessCount;
private static ExampleSingleton instance = new ExampleSingleton();
private ExampleSingleton() {
System.out.println("I, the ExampleSingleton, am being created");
}
public static ExampleSingleton getInstance() {
System.out.println("The sole instance of ExampleSingleton is being retrieved")
}
}
ExampleTest.java
public class ExampleTest {
public static void main(String[] args) {
ExampleSingleton s = ExampleSingleton.getInstance();
System.out.println("The ExampleSingleton has been "
+ "accessed via the getInstance() method "
+ s.accessCount()
+ " time(s)");
s = ExampleSingleton.getInstance();
System.out.println("The ExampleSingleton has been "
+ "accessed via the getInstance() method "
+ s.accessCount()
+ " time(s)");
}
}
So I can get the following output output
You may use static AtomicInteger class type variable and increment it when you are retrivig the instance:
public class ExampleSingleton {
private static AtomicInteger accessCounter = new AtomicInteger(0);
public static int getAccessCount() {
return accessCounter.get();
}
private static ExampleSingleton instance = new ExampleSingleton();
private ExampleSingleton() {
System.out.println("I, the ExampleSingleton, am being created");
}
public static ExampleSingleton getInstance() {
accessCounter.getAndAdd(1);
System.out.println("The sole instance of ExampleSingleton is being retrieved");
return instance;
}
}
public class ExampleTest {
public static void main(String[] args) {
ExampleSingleton s = ExampleSingleton.getInstance();
System.out.println("The ExampleSingleton has been "
+ "accessed via the getInstance() method "
+ s.getAccessCount()
+ " time(s)");
s = ExampleSingleton.getInstance();
System.out.println("The ExampleSingleton has been "
+ "accessed via the getInstance() method "
+ s.getAccessCount()
+ " time(s)");
}
}
This block of code should be placed inside the ExampleSingleton
class, and incrementCounter()
should then be called from getInstance()
.
The AtomicInteger
is a class that wraps an integer and supports concurrency, so its far safer than using a standard Integer
or Long
. The variable itself is private static
, so that it's read-only and exists with the singleton class versus the singleton instance.
private static AtomicInteger counter = new AtomicInteger(0);
public Integer getCount() {
return counter.get();
}
/**
* @return the new counter
*/
private Integer incremenetCounter() {
return counter.incrementAndGet();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.