How can I get the application instance when using javafx?
Normally you launch an application this way:
public class LoginForm {
public static void main(String[] args) {
LoginApplication.launch(LoginApplication.class, args);
}
}
The method launch does not return an instance of application.
Is there a way I could get the instance?
I was just trying to find an easy, logical way to do exactly this. I haven't. It would be really nice if there was an Application.getApplicationFor(AppClass.class) that managed some singletons for you--but no.
If we restrict the problem space it's pretty easy to solve. If we make the class a singleton, then it's cake... A simplified singleton pattern should work fine:
class MyApp extends Application
{
public static MyApp me;
public MyApp()
{
me=this;
}
...
}
me can be null if it hasn't been instantiated by the system yet. It would be possible to protect against that with more code.
... implementing code...
Just implemented this--seems to work (barring any strange threading situations)
I have a slightly different situation, I'm wedging a javaFX screen into an existing swing GUI. It works fine, but I need to ensure that Application.launch is only called once. Adding this requirement, my final solution is thus:
(Sorry but the syntax has some groovy in it, should be easy for any Java user to translate)
class MyClass extends Application{
private static MyClass instance
public MyClass() {
instance=this
}
public synchronized static getInstance() {
if(!instance) {
Thread.start {
// Have to run in a thread because launch doesn't return
Application.launch(MyClass.class)
}
while(!instance)
Thread.sleep(100)
}
return instance
...
} // class
This manages blocking until Application.launch has completed instantiating the class, getting instances from other locations and ensuring that Application.launch gets called exactly once as long as getInstance has been called at least once.
Related
For performance reasons, I have a class that stores a Map whose key is a Class<?> and its value is function of that class's fields. The map is populated during code execution according to the type of the calling object. The above is a generalization/simplification
public class Cache {
private static final Map<Class<?>, String> fieldsList = ...;
//Synchronization omitted for brevity
public String getHqlFor(Class<?> entity){
if (!fieldsList.containsKey(entity))
fieldsList.put(entity,createHql(entity));
return fieldsList.get(entity);
}
}
During development, thanks to the help of Jrebel, I often make modifications to classes by changing entire properties or just their names. I can continue development just fine. However, if I already put a value into the cache it will be stale forever.
What I am asking here is if it is possible to intercept the event that a class in the classpath has changed. Very broad... But my specific problem is very simple: since I have such a need only during development, I just want to wipe that cache in case any class in my classpath changes.
How can I accomplish this? I don't need to do anything special than intercepting the event and simply wiping the cache
JRebel has a plugin API that you can use to trigger code on class reloads. The tutorial complete with example application and plugin available here: https://manuals.zeroturnaround.com/jrebel/advanced/custom.html
The JRebel plugin is a self-contained jar built against the JRebel SDK, which is attached to the running application via the JVM argument -Drebel.plugins=/path/to/my-plugin.jar. The JRebel agent attached to the application will load and start plugins from this argument.
If the application is not started with the JRebel agent, the plugin is simply not loaded.
In your example you want to register a ClassEventListener that will clear the Cache.fieldsList map. As it is a private field, you need to access it via reflection or add a get/clear method via a ClassBytecodeProcessor
public class MyPlugin implements Plugin {
void preinit() {
ReloaderFactory.getInstance().addClassReloadListener(new ClassEventListenerAdapter(0) {
#Override
public void onClassEvent(int eventType, Class<?> klass) throws Exception {
Cache.clear();
}
});
}
// ... other methods ...
}
And to clear the map
public class CacheCBP extends JavassistClassBytecodeProcessor {
public void process(ClassPool cp, ClassLoader cl, CtClass ctClass) {
ctClass.addMethod(CtMethod.make("public static void clear() { fieldsList.clear(); }", ctClass));
}
}
However a better option is to only clear/recalculate the single class entry on class reload if possible. The example didn't display whether the info computed from one class depended on superclass infos, but if this is true, the JRebel SDK has methods to register a reload listener on the class hierarchy as well.
There is an existing class ClassValue which already does the job for you:
public class Cache {
private final ClassValue<String> backend = new ClassValue<String>() {
#Override
protected String computeValue(Class<?> entity) {
return createHql(entity);
}
};
public String getHqlFor(Class<?> entity){
return backend.get(entity);
}
}
When you call get, it will call computeValue if this is the first call for this specific Class argument or return the already existing value otherwise. It does already care thread safety and for allowing classes to get garbage collected. You don’t need to know when class unloading actually happens.
I have a class, which has an Initialize method, which creates a bunch of tables in a database. This class looks like this:
public class MyClass
{
private bool initialized = false;
public void Initialize()
{
if(!initialized)
{
//Install Database tables
initialized = true;
}
}
public void DoSomething()
{
//Some code which depends on the database tables being created
}
public void DoSomethingElse()
{
//Some other code which depends on the database tables being created
}
}
The two methods DoSomething and DoSomethingElse need to make sure that the Initialize method has been called before proceeding because they depend on having the tables in the database. I have two choices:
Call the Initialize method in the constructor of the class - this does not seem like a good idea because constructors should now call methods, which are non-trivial and could cause an exception.
Call the Initialize method in each of the two methods - this does not seem like a great solution either especially if there are more than a handful of methods.
Is there a design pattern which could solve this in a more elegant way?
I would use a static factory method in which Initialize is invoked, and make the constructor private, to force use of the static factory method:
public class MyClass
{
private MyClass() { ... }
public static MyClass createInstance() {
MyClass instance = new MyClass();
instance.Initialize();
return instance;
}
}
Also, I would remove the initialized variable - in part because you don't need it any more - but also because it requires some means of guaranteeing visibility (e.g. synchronization, volatile or AtomicBoolean) for thread safety.
I think that Miško Hevery's blog post on (not) doing work in constructors is an interesting read.
I would separate the installation of the database from the definition of tasks that depends on it:
static factory could be used for the database installation as pointed out by #andy-turner
and the repository pattern to do work on the database
I suggest this solution because if i understand correctly, you are concerned about the high number of tasks that depends on the database.
Using the dependency injection pattern the repository can get a reference to the database, so in your bootstrapping code you can execute the database installation once and then inject the reference to the database in all the repositories that depends on it.
I would recommend using a collaborator that does the initialisation. That way MyClass can easily be tested by substituting a mock for the initialiser collaborator. For example:
public class MyClass {
public MyClass(MyClassInitialiser initialiser) {
initialiser.initialize();
}
public void DoSomething() {
//Some code which depends on the database tables being created
}
public void DoSomethingElse() {
//Some other code which depends on the database tables being created
}
}
Or an alternative solution, the idea here is that you're breaking the single responsibility principle in MyClass. There is non-trivial initialisation behaviour (installing database tables) and behaviour on those tables in the same class. So you should separate those responsibilities into two different classes and pass one in as a collaborator to the other.
public class MyClass {
DatabaseCollaborator collaborator;
public MyClass(DatabaseCollaborator collaborator) {
this.collaborator = collaborator;
}
public void DoSomething() {
//Some code which depends on the database tables being created
collaborator.someMethod();
}
public void DoSomethingElse() {
//Some other code which depends on the database tables being created
collaborator.anotherMethod();
}
}
public class DatabaseCollaborator {
DatabaseConfig config;
public DatabaseCollaborator(DatabaseConfig config) {
this.config = config;
}
public void someMethod() {
}
public void anotherMethod() {
}
}
public class DatabaseConfig {
public DatabaseConfig() {
// initialize
}
}
When I want a class whose instances must be initialized exactly once but I want to defer initialization until right before it's necessary (at which point the caller may fail to call an Initialize function, find it inconvenient to do so, or etc.), I do it similar to how you've started out with your code, but I make the initialization method private and name it something like "EnsureInitialized". It uses a flag to track and early exit if initialization has already been done, and all functions which depend on initialization already having happened just call that function as their first line (after argument-checking).
If I expect the caller to control when this instance's initialization is done, I make the method public, name it "Init", track whether it has been run with a flag, handle idempotence or max-run-once inside the Init method however is appropriate for that class, and all methods which depend on Init having already been run will call a different, private method named "AssertIsInitialized" which will throw an exception with text like "Must call init on {class name} instance before using this function".
My goal with these different patterns is to be unambiguous about each method's expectations and operation regarding initialization within the class instance lifecycle, and provide discoverability (of the design or code bugs using it) and automatic behavior (in the case of the self-initializing class in my first paragraph) wherever I think each is most appropriate to what the rest of the application is doing.
I'm developing a Play Framework 2 application in Java, and I'm wondering if I can use static helper classes.
For example, I want to know if a user is logged and have completed its profile. This test take a few lines, may be subject to change, and is used a lot in the application.
So I write a class with these tests in one method with one argument (the Session object) that I use everywhere.
But I have to instantiate a class each time to use the method, so at scale it may be inefficient. Is it safe to make it static ? If it is, what other play object can I use safely as a parameter ?
When you say "test", I assume you mean some checking logic instead of unit tests.
In that case, you can use dependency injection instead of static helpers.
https://www.playframework.com/documentation/2.3.x/JavaInjection
The above link shows an example of how to use Guice to inject your controller when processing requests.
So previously your controller would be:
public class Application extends Controller {
public static Result index() {
if (YourStaticHelper.yourStaticMethod.isOk()) {
return ok("It works!");
}
else {
return forbidden("NO");
}
}
}
Now it would become:
public class Application extends Controller {
#Inject
YourStaticHelperInterface checker;
public Result index() { // no longer static
if (checker.isOk()) {
return ok("It works!");
}
else {
return forbidden("NO");
}
}
}
The difference is in the previous one if you somehow need a new helper, you would have to change the controller code to adapt it to the change, whereas in the second you just need to inject a different implementation at runtime as isOk() there becomes a contract in the interface.
The benefit? Who knows. If I'm writing something completely myself at home or the controller code is actually tightly coupled with the helper, I would choose the first. If I'm working with others in a company, I would pick the second. It's all about software engineering shit but that's how things work.
I am currently working on a project that needs to be refactored (it was not written by me and the original developer is not around). I see in that application that rather many classes have only private constructors and one or more static methods (getter/setter of the current class object). They also have non-static methods. I give you one example:
Class UndoManager that manages the actions taken on the application for performing undo/redo. It has only private constructors. When the application is loaded, UndoManager.setManager() is called. This method loads the undo history from a file or constructs a new one using a private constructor.
Later, every class can access this instance of UndoManager with syngronized static method .getManager().
In code:
public class UndoManager extends SimpleObservable<UndoManager> {
private static UndoManager instance;
private final Stack<Action> undoHistory;
private final Stack<Action> redoHistory;
public synchronized static void setManager(UndoManager undoManager) {
UndoManager instance = getManager();
instance.clear();
instance.undoHistory.addAll(undoManager.undoHistory);
instance.redoHistory.addAll(undoManager.redoHistory);
instance.notifyObservers(instance);
}
public synchronized static UndoManager getManager() {
if (instance == null)
instance = new UndoManager();
return instance;
}
private UndoManager() {
this.undoHistory = new Stack<Action>();
this.redoHistory = new Stack<Action>();
}
/.../
}
In this application multiple classes are used like this. They are not helper classes but classes that should have only one instance.
My question is:
is this kind of access good style? If not, how would you refactor the class and it's access?
I'm sorry if it is a duplicate, but I have searched in stackoverflow and google for a while but somehow I didn't find a satisfying answer. Thank you for any help.
This looks like a singleton pattern.
It is part of the great familly of designs patterns you might know them.
The point of this is to ensure that there is only one instance of this object used throughout your application. Indeed when you call getManager() it will return a new instance the first time and next times it will return the formerly created instance.
it's a design pattern that called Singleton. it's a lazy load and used for managers classes and service classes for example. they are for classes that you want an instance but only one instance of them.
there is usually a method to get the instance like your getManager method and a private constructor like you have
I'm creating a library that will be included as a jar, so it won't contain a main method. I'm wondering what is the best practice for bootstrapping Guice in this case. I have one top level singleton.
public class TestManager
{
private TestManager()
{
}
public static TestManager getInstance()
{
// construct and return singleton
}
public void createSomeObjects()
{
}
}
Where should I bootstrap Guice? I was thinking that in the constructor that I could call Guice.createInjector(new Module()); but it wouldn't inject any of the objects created in createSomeObjects().
Is there a common way to do this when you don't have a main method()?
Cheers.
Much like logging configurations, if this is a true library then your options are pretty much this:
Tell the library user that they are responsible for bootstrapping Guice themselves.
Provide a library initialization method that takes care of bootstrapping Guice if they want to use your library
Trying to make the library super-smart to do self-configuration often ends up with somewhat inflexible, hard to test class hierarchies.
If you're just using Guice in the scope of your library and not for the whole application then you could use a static block in the TestManager class.
This strategy assumes that the application is going to call TestManager.getInstance() at some point and that it is the only entry point into your API.
#Singleton
class TestManager {
private static final TestManager INSTANCE;
static {
INSTANCE = Guice.createInjector(new Module()).getInstance(TestManager.class);
}
private TestManager() {
}
public static TestManager getInstance() {
return INSTANCE;
}
#Inject
public void createSomeObjects(YourDependencies ...) {
// Do something with dependencies
}
}
This is not what you should do, but what you could do:
Let key classes in your library extend or otherwise reference a class that initializes everything in a static block. This is a very dirty hack, but if you make sure your api can't be accessed without the classloader loading your initializer class you should be on the safe side.
You could make it a bit cleaner if you used AspectJ and injected a private Member of the initializer type into all classes in your library (without touching the java code), but it would still be a hack.