I have Constants class in my web application.
I want to monitor Constants class using Jconsole.
I have #ManagedResource used annotation for Constants class and #ManagedAttributefor setter method.
If I will use #ManagedAttribute for static method then it will not displayed in Jconsole and for non-static method it works fine.
Can you please provide explanation why it was not working with static method?
Following is my Constants class.
#ManagedResource(
objectName = "Sample:name=ActivityQueueUtil",
description = "Allows modifying all settings."
)
public class ActivityQueueUtil {
private static volatile ActivityQueueUtil instance;
public static ActivityQueueUtil getInstance() {
if (instance == null ) {
synchronized (Constants.class) {
if (instance == null) {
instance = new ActivityQueueUtil();
}
}
}
return instance;
}
public void initInstance() {
instance = this;
}
private int currentWorkerCount = 0;
private int currentQueueSize = 0;
private int currentRetryQueueSize = 0;
#ManagedAttribute(description = "Current number of worker threads.")
public static int getCurrentWorkerCount() {
return currentWorkerCount;
}
public void setCurrentWorkerCount(int currentWorkerCount) {
this.currentWorkerCount = currentWorkerCount;
}
#ManagedAttribute(description = "Number of activities in the queue")
public int getCurrentQueueSize() {
return currentQueueSize;
}
}
Here it works for setCurrentWorkerCount,getCurrentQueueSize but not working for getCurrentWorkerCount
Related
In my Android application I have to initialize a lot of static Objects before the first Activity starts. From what I know, static variables are initialized when classes are loaded. So, with time the amount of static objects in project began to grow and now I'm getting NullPointerExceptions. In my case static objects may call other static objects in their constructors. So my question is: could some static variables be initialized before variables they depend on and thus cause NullPointersExceptions? Is that possible?
Code example :
private static class HardwareManagersHolder implements HardwareManagers, IManagers {
private final AtomicBoolean senderAcquire = new AtomicBoolean(false);
private final AtomicInteger receiverAcquire = new AtomicInteger(0);
public IAudioManager audioManager;
public IVideoManager videoManager;
public IVibrationManager vibrationManager;
public IBatteryHelper batteryHelper;
#Override
public void configureManager() {
audioManager = AudioHelper.getInstance();
vibrationManager = VibrationManager.getInstance();
videoManager = VideoManager.getInstance();
batteryHelper = BatteryHelper.getInstance();
}
And an Object Holder:
public class VideoManager implements IVideoManager {
private static class VideoManagerHolder {
public static final VideoManager VIDEO_MANAGER_INSTANCE = new VideoManager();
}
public static VideoManager getInstance() {
return VideoManagerHolder.VIDEO_MANAGER_INSTANCE;
}
}
I tried to reconstruct your exception with the snippets you provided. I used the following code:
public interface IVideoManager {}
public class VideoManager implements IVideoManager {
private static class HardwareManagersHolder {
public IVideoManager videoManager;
public void configureManager() {
videoManager = VideoManager.getInstance();
}
}
private static class VideoManagerHolder {
public static final VideoManager VIDEO_MANAGER_INSTANCE = new VideoManager();
}
public static VideoManager getInstance() {
return VideoManagerHolder.VIDEO_MANAGER_INSTANCE;
}
public static void main(String[] arg) {
System.out.println("Start test");
HardwareManagersHolder h = new HardwareManagersHolder();
h.configureManager();
if (h.videoManager == null) {
System.out.println("VideoManager is null");
}
System.out.println("Test finished");
}
}
This code works on my machine. If this code is not working on yours, there is some other fault.
Are you initializing them in a static constructor? They would get called first for precisely this reason.
static
{
VIDEO_MANAGER_INSTANCE = new VideoManager();
}
I have n child classes inherit from Parent. I need to count all child objects and when all will be done trigger listener. Unfortunately I'm getting an errors: "Static member 'childCountListener' accessed via instance reference" and "'this' cannot be referenced form a static context". I know I cannot use "this" because I don't have object of this class but I have no idea how to achieve this.
Parent:
public abstract class Parent {
protected static int childCount = 0;
private static ChildCountListener childCountListener;
public Parent() {
// (...)
incrementChildCount();
}
public void doSomething() {
// (...)
decrementChildCount();
}
public static int getChildCount() {
return childCount;
}
private void incrementChildCount() {
childCount++;
}
private void decrementChildCount() {
childCount--;
if (childCount < 1) {
childCountListener.allDone();
}
}
public static void addChildCountListener(ChildCountListener childCountListener) {
this.childCountListener = childCountListener;
// Static member 'childCountListener' accessed via instance reference
// 'this' cannot be referenced form a static context
}
public interface ChildCountListener {
void allDone();
}
}
Remove the this from addChildCountListener
public static void addChildCountListener(ChildCountListener childCountListener) {
Parent.childCountListener = childCountListener;
}
or
public static void addChildCountListener(ChildCountListener aChildCountListener) {
childCountListener = aChildCountListener;
}
Singleton is a service that require injection of authentication and configuration data. I end with class:
class SingleService {
private String conn;
private String user;
private String pass;
private SingleService() {
// Can throw exception!!
conn = Config.getProperty("conn");
user = Config.getProperty("user");
pass = Config.getProperty("pass");
// Can throw exception!!
internalService = tryConnect(conn, user, pass);
}
private static SingleService instance;
public static void init() {
instance = new SingleService();
}
public static synchronized SingleService getInstance() {
if (instance == null) init();
return instance;
}
}
Dedicated init() method used for exception handling during application startup to early detect initialization errors early because later we just call getInstance() and doesn't expect to get errors:
class App {
public static void main(String args[]) {
try {
Config.init("classpath:auth.properties");
SingleService.init();
} catch (Exception ex) {
logger.error("Can't init SingleService...");
System.exit()
}
doJob();
}
private static void doJob() {
SingleService.getInstance().doJob();
}
}
I worry about init() method and singleton class signature. Fill that class was designed badly but don't understand what's wrong.
Is it possible to move away initialization from getSingleton() and synchronized and preserving control on exception during initialization?
This is how I would code it so you can throw exceptions if needed but still have a thread safe singleton.
enum SingleService {
INSTANCE;
private String conn;
private String user;
private String pass;
private SingleService instance;
public synchronized void init(Config config) throws SomeException {
// don't leave in a half state if we fail.
internalService = null;
conn = config.getProperty("conn");
user = config.getProperty("user");
pass = config.getProperty("pass");
internalService = tryConnect(conn, user, pass);
}
public synchronized void methodForService() {
if (internalService == null) throw new IllegalSateException();
// do work.
}
}
SingleService ss1 = SingleService.getInstance();
SingleService.init();
SingleService ss2 = SingleService.getInstance();
So ss1 is a different object than ss2 which is not what Singleton is designed for. If ss1 is modified at anytime ss2 will remain unaffected.
Fist of all you souhld not expose object creation method. If you want to check something, than go with asserts or any operation that will not corrupt instance object.
public static void checkIfValid() {
assert Config.getProperty("conn");// do not corrupt instance object
assert Config.getProperty("user");
assert Config.getProperty("pass");
}
public static synchronized SingleService getInstance() {
if (instance == null){ // only here you can initiate instance object
instance = new SingleService();
}
return instance;
}
My production code for problem I have sought:
public abstract class AbstractCaller<Port> {
abstract protected Port createPort();
protected init() {
Port port = createPort();
// heavy use of introspection/reflection on **port** object.
// Results are used later by **call** method.
}
public call() {
// Reflection based on data collected by **init** method.
}
}
public class ConcreteCaller extends AbstractCaller<ConcretePort> {
private ConcreteService service = new ConcreteService();
#Override
protected ConcretePort createPort() {
return service.getPort();
}
private static class Holder {
public static ConcreteCaller INSTANCE;
static {
INSTANCE = new ConcreteCaller();
INSTANCE.init();
}
}
public static Caller getInstance() {
return Holder.INSTANCE;
}
}
Abstract class has common init method that can only operate on fully initialized concrete class. Inner static class is used for lazy instantiation and perform init invocation.
There is no way to apply init method from superclass constructor to avoid need to call init in each implementation.
I need a class able to return instances of itself. I like method used by a singleton pattern that return only once instance of class. But I need that it return more than one instance.
This is my singleton pattern. How can I modify it to get it able to return more than one instance?
public class GrigliaImpl implements Griglia{
private static GrigliaImpl istanza;
private JTextField[][] griglia;
private Color color;
public GrigliaImpl(){
}
#Override
public int getColumn() {
return griglia[0].length;
}
public JTextField[][] getMatrice(){
return this.griglia;
}
#Override
public int getRow() {
return griglia.length;
}
#Override
public void setColor(Color x) {
this.color=x;
}
#Override
public Color getColor() {
return color;
}
public void set(int row,int column){
this.griglia= new JTextField[row][column];
}
public static GrigliaImpl getIstanza(){
if(istanza == null){
istanza = new GrigliaImpl();
}
return istanza;
}
}
You are talking about the factory pattern:
public class MyClass() {
}
public class MyClassFactory() {
public static getNewInstance() {
return new MyClass();
}
}
The factory method can be included in your class, you don't need a separate factory class.
Your requirements are controversial. If you want to have a singleton - then you will have one instance of this class by definition. If you want to have many instances, then it can't be singleton.
To create a singleton, you need to make your constructor private and add static method to get an instance of your class, which is kept as a static field. (http://en.wikipedia.org/wiki/Singleton_pattern)
If you want to return the same instance of class, after invoking its methods, consider using Builder pattern (http://java.dzone.com/articles/dive-builder-pattern).
public class GrigliaImpl implements Griglia {
private static GrigliaImpl instance;
private GrigliaImpl() {
}
public static GrigliaImpl getInstance() {
if (instance == null) {
instance = GrigliaImpl();
}
return instance;
}
public GrigliaImpl doSomething() {
// do something
return this;
}
}
Default behavior of every class that has a public contructor is to create and return new instances of that class using new operator. but if you specifically want instances through a getInstanceMethod than make constructor private and
replace
public static GrigliaImpl getIstanza(){
if(istanza == null){
istanza = new GrigliaImpl();
}
return istanza;
}
with
public static GrigliaImpl getIstanza(){
return new GrigliaImpl();
}
But to me that does not serve any purpose. But you can still do it :)
I have an example code of Singleton class inheritance below. However, I've not forseen if there's any hidden issue might happen with this code. Can someone analyze and give me a hint?
interface ChairIF {
public int getLeg();
public void test();
}
class ChairImpl implements ChairIF {
private static final Lock lock = new ReentrantLock();
private static ChairIF instance = null;
public static ChairIF getInstance(String clazzName) {
//get class by clazzName
Class clazz = null;
try {
clazz = Class.forName(clazzName);
} catch (ClassNotFoundException ex) {
lock.lock();
try {
if (instance == null) {
instance = new ChairImpl();
}
} finally {
lock.unlock();
}
}
//init singleton instance of clazzName
if (instance == null) {
lock.lock();
try {
if (instance == null) {
instance = (ChairIF) clazz.newInstance();
} else {
if (instance.getClass() != clazz) {
instance = (ChairIF) clazz.newInstance();
}
}
} catch (Exception ex) {
instance = new ChairImpl();
} finally {
lock.unlock();
}
} else {
lock.lock();
try {
if (!instance.getClass().getName().equals(clazz.getName())) {
instance = (ChairIF) clazz.newInstance();
}
} catch (Exception ex) {
instance = new ChairImpl();
} finally {
lock.unlock();
}
}
return instance;
}
public int getLeg() {
return 4;
}
public void test() {
throw new UnsupportedOperationException();
}
}
class ThreeLegChair extends ChairImpl {
public ThreeLegChair() {}
public int getLeg() {
return 3;
}
public void test() {
int i = 0;
while(i < 10000) {
System.out.println("i: " + i++);
}
}
}
class NoLegChair extends ChairImpl {
public NoLegChair() {}
public int getLeg() {
return 0;
}
public void test() {
int j = 0;
while(j < 5000) {
System.out.println("j: " + j++);
}
}
}
public class Test {
public static void main(String[] args) {
System.out.println(ChairImpl.getInstance("ThreeLegChair").getLeg());
System.out.println(ChairImpl.getInstance("NoLegChair").getLeg());
/***
TODO: build logic to run 2 test() simultaneously.
ChairImpl.getInstance("ThreeLegChair").test();
ChairImpl.getInstance("NoLegChair").test();
****/
}
}
As you can see, I did put some test code in 2 subclasses. ThreeLegChair is to loop from 0 to 10000 and print it out. NoLegChair is to loop only from 0 to 5000 and print it out.
The result I got in the console log is correct. ThreeLegChair printed i from 0 to 10000. NoLegChair printed j from 0 to 5000.
Please share me your thought :)
Singleton pattern is achieved using the concept of private constructor i.e. the class itself is responsible for creating single instance of the class (singleton) and preventing other classes from creating objects.
Now as the constructor is private, you cannot inherit the singleton class at first place. In your case, I do not see a private constructor which makes it vulnerable to object creation from other classes accessing it.
Singleton pattern examples:
Using enumerations in Java
enum SingletonEnum {
SINGLE_INSTANCE;
public void doStuff() {
System.out.println("Singleton using Enum");
}
}
Lazy initialization approach
class SingletonClass {
private static SingletonClass singleInstance;
private SingletonClass() {
// deny access to other classes
}
// The object creation will be delayed until getInstance method is called.
public static SingletonClass getInstance() {
if (null == singleInstance) {
// Create only once
singleInstance = new SingletonClass();
}
return singleInstance;
}
}
However, the above example may not guarantee singleton behavior in multithreaded environment. It is recommended to use double checked locking mechanism to ensure that you have created a single instance of this class.
The code you post isn't an implementation of the singleton pattern.
Quite simply, you can do:
ChairImpl ci = new ChairImpl();
And instantiate as many as you want.
The traditional method of implementing the singleton pattern is the make the constructor private, have a private static field that holds the single instance of the class, and a static getInstance() method that either instantiates that instance or returns the existing one. Making that threadsafe involves either declaring it synchronized or using a locking scheme.
The private constructor bit makes it so you can't inherit from it.
That said, in Java the preferred way is using an enum which provides all the hard parts for free:
public enum MySingleton {
INSTANCE;
public int getLeg() {
return 4;
}
}
And using as:
MySingleton ms = MySingleton.INSTANCE;
int leg = ms.getLeg();
Singletons usually have private constructor. Your class is not following proper Singleton pattern. otherwise you would not be inherit your singleton class.