java - how to persist variable in JVM - java

I have an odd situation where i want to be able to be able to persist a variable in memory.. like a global variable I can pin in the JVM.
Is this possible? I remember doing something similar in college, but can't find it by googling. I have a logic problem that has some artificial constraints that make this the best possible solution.
EDIT 1:
I will need to update the value of the variable.
EDIT 2 :
I appreciate the responses guys. I'm a .net programmer and hadn't used java since college. Thanks again.

Yes, using a static field:
public class GlobalVariableHolder {
public static int globalVariable;
}
Note, however, that this is considered a bad practice and can lead to unexpected results that are hard to debug. The way to not use a global variable is to pass it around as an argument or methods where you need it.
If you are still sure you need this, in order to guard yourself as much as possible, use synchronization. Even better, if the variable is going to be primitive (int, long, etc), you can use AtomicInteger's getAndAdd() or addAndGet() method.

Usually you will end up storing these things in some kind of a global class--a class that is accessible from anywhere and has a controlled number of instances.
Singletons are commonly used for this. If you look up the pattern for a singleton and store your variable in that singleton (add a setter and a getter) you are on your way.
Doing this (as opposed to a public static variable) will give you some level of access control and traceability--for instance you can put debug statements in the getter if you find you are getting unpredictable results.
In the long run setters and getters and singletons are all bad code smells but no where near as bad as a settable public variable.
Later you may want to move the code that manipulates that variable into the singleton object and possibly convert the singleton to something you can fetch via IOC, but having a singleton is a much better place to start than with a public static.

Do you mean something that will exist across multiple invocations of java.exe, or do you mean a single variable that will be the same location in memory regardless of which thread within java.exe access it? Or do you mean a variable that can only be accessed if you're using JRockit? Or maybe just the JVM on your dev machine, but not on another system?
In the first case, you'd need another way to store it, like a config file.
In the second case, like Bozho says, use the static keyword.
In the third case, you'd probably need to use the System class and determine the JVM manufacturer (Assuming that's available from System - I'm not sure off the top of my head, and you'll learn more by looking up the API yourself).
In the fourth case, you're pretty much back to a config file.

Its not going to win any awards but this should work:
package mypackage;
public class MyGlobal {
public static String MY_GLOBAL_VAR = "my variable";
}
Any class within that JVM instance would be able to access MyGlobal.MY_GLOBAL_VAR.
Updated to allow update.

Related

in java how to replace an immutable object

how
lets say i have this class
#ImmutableWannabe
public class ConfigurationHolder {
#ImmutableButHowToMakeSureNoTwoThreadsOverrideOneEachOtherWhenReplacingReference
private Map<System, Configuration> mySysConfig = ImmutableMap.builder<>getSomeConfigurations....build();
ConfigurationHolder(copy constructor) {
mySysConfig = ImmutableMap.builder().of(inputSysConfig);
}
}
Now lets say one of the systems configuration has updated and i need to update this map of however I need to do it in a thread safe way. which means if two threads try to update the same configuration of same system data should be consistent and they should not override one each other.
How did immutability help me here? As far as i can see i still need to do locking if yes how to do it properly?
so my general question is: isn't it the case that any immutableObject which can change over system time will cause us to need to lock the code that will need to change its ImmutableObjectHolder? I don't get it...
can someone please give a proper example of an ImmutableMap + Holder for that Map + proper "client" code that knows to update this ImmutableMapHolder with updates to the internal Map?
thanks
Assuming your map is some instance variable, the simplest way it to make it volatile. Alternatively, make a getter and setter for it and make them synchronized. i.e., use standard techniques. And note that this won't help if the client tries to be clever and cache the value in a local variable. (I've bitten myself with this bug a couple of times.)
I guess as an alternative you could setup some MyImmutableChanged event/listener.
And, you are correct, immutability doesn't solve every threading problem.

Using static class methods in multi-threaded programming

I am building a webcrawler which is using two classes: a downloader class and an analyzer class. Due to my design of the program I had some methods which I outsourced to a static class named utils (finding the link suffix, determining if I should download it given some variables, etc.). Since at a certain time there is more than one downloader and more than one analyzer I'm wondering whether they can get a wrong answer from some static method in the utils class.
For example, say the analyzer needs to know the link suffix - it's using the utils.getSuffix(link) method. At that same time the OS switches to some downloader thread which also needs to get some link suffix and again uses utils.getSuffix(link). Now the OS switches back to the analyzer thread which does not get the correct response.
Am I right?
In case I'm right should I add synchronized to every method on the utils class? Or should I just use the relevant methods in every thread to prevent that kind of scenario even though I'm duplicating code?
This entirely depends on the implementation of the method. If the method uses only local variables and determines the suffix based on the parameter you give it, all is well. As soon as it needs any resource that is accessible from another thread (local variables and parameters are not) you'll need to worry about synchronization.
It seems to me you're using statics as utilities that don't need anything outside their own parameters; so you should be safe :)

Java-Design: Enum state?

I realize (having read other posts on SO as well) that it's bad design (or better said in my case it would also not make sense) to add state to enum constants.
Nevertheless i am finding myself right now in a situation where i need something similar to this.
An application i am writing uses error-constants (enum), which i am using to indicate errors by adding them to a Map<Error, ErrorInfo> (note that these are not application-errors, but "Errors" that are part of the application).
Well - i now realize that i actually also need to indicate an ErrorLevel of INFO, WARN, FATAL for these.
Since the ErrorLevel of an Error depends on the context it occurred in, i cannot statically assign ErrorLevel's to the Error-enums, in other words, an Error.E1 can be of ErrorLevel.WARN one time, but might be ErrorLevel.FATAL another time.
I am thinking about how i could best incorporate this ErrorLevel in my design, but all i have come up with up to now is, to introduce a new class which simply wraps an Error and an ErrorLevel and use it within the Map instead of Error.
Since Errors and their severity seem to me something that must be quite common, i am sure that there are smarter way to do this, so i would greatly appreciate your ideas on how to design this better.
--qu
If I understood your problem correctly, putting a transient state to the enum won't do the trick. As there is only one instance per enum-type by changing the error-level you would not only change it for the current error you are assessing but for all errors of the same type in the application.
You wrote, the errorlevel is depending on the context and at the same time that ErrorInfo describes the context of the occurance of the error. If you can calculate the errorlevel based on the errortype and the context, I would suggest some static method
public static ErrorLevel getLevel(Error, ErrorInfo) {
//..
}
I do not agree in total that it is always bad design adding mutable state to enums. Enums are like Singletons and whenever it makes sense to use a stateful singleton in your application, you can do the same with enum. Like with singletons we just have to keep in mind, that a state change has a pretty global effect.
For sure, stateful enums won't help in your case, because you want context specific error levels.
As an alternative, consider using a simple multimap:
Map<Context, Map<Error, ErrorLevel>> errors;
The idea is to store multiple maps for different contexts. So for a known context (I quickly invented a type...) you get the context specific parameter map.

What's the proper way of declaring project constants in Java?

This may seems a silly question for Java developers, however, I'm new to Java, and my background is from low level c.
I used to include an header file with all the constants that were relevant for my projects. (usually #define's).
I'm working on a big Java project now, and there a few constants I need to make global (they fit in more than one class, and used in various parts of the project )
It makes it hard for me to decide where to put it, should I declare the same constant few times, one in each class ?
A lot of framework, uses XML files to declare constants & definitions for the framework (Hibernate, Log4J, etc.) Is it wise to use this kind of technique in my project ? if so, how can it be done easily ?
As with many things, there are many ways to do it. One thing you should not do is declare them multiple times - that's just plain silly. :P
Everything has to be in a class in Java, so either:
Pick a "main" class (say I have a project called "FTPServerApp" - I could put them there)
Create a "Util" class that contains all of them
When you figure out where to put them, declare them all this way:
public static final [type] [NAME_IN_ALL_CAPS] = [value];
This will
make them available to all your project code, anywhere (public)
only one copy of the value exists across all instances of the class (static)
they cannot be changed (final).
The ALL_CAPS_FOR_CONSTANT_NAMES, separated by underscores, is the convention in Java.
So, if this was declared in a class called FTPServerAPP, and you had a constant called SERVICE_PORT it might be:
public class FTPServerApp {
public static final int SERVICE_PORT = 21;
...
}
...and you would access it, from any class, like this...
FTPServerApp.SERVICE_PORT
Take a look at enumeration types (http://download.oracle.com/javase/tutorial/java/javaOO/enum.html) They are supposed to provide a mechanism to supply constants without defining a concrete class (or an Interface with the desired constants, as is another option that people use).
One other technique I find helpful (similar to the FTPServerApp example given above) is to define a Context for whatever subsystem/component/etc... that holds not only the constants needed by components in that system, but can hold any state that you want to make more visible or don't want individual components to hold. I believe this is along the lines of one of the GoF patterns, but it has been so long since I have looked at that book that I can't be certain (and I am too lazy to look it up right now!)

In Java, how can I construct a "proxy wrapper" around an object which invokes a method upon changing a property?

I'm looking for something similar to the Proxy pattern or the Dynamic Proxy Classes, only that I don't want to intercept method calls before they are invoked on the real object, but rather I'd like to intercept properties that are being changed. I'd like the proxy to be able to represent multiple objects with different sets of properties. Something like the Proxy class in Action Script 3 would be fine.
Here's what I want to achieve in general:
I have a thread running with an object that manages a list of values (numbers, strings, objects) which were handed over by other threads in the program, so the class can take care of creating regular persistent snapshots on disk for the purpose of checkpointing the application. This persistor object manages a "dirty" flag that signifies whether the list of values has changed since the last checkpoint and needs to lock the list while it's busy writing it to disk.
The persistor and the other components identify a particular item via a common name, so that when recovering from a crash, the other components can first check if the persistor has their latest copy saved and continue working where they left off.
During normal operation, in order to work with the objects they handed over to the persistor, I want them to receive a reference to a proxy object that looks as if it were the original one, but whenever they change some value on it, the persistor notices and acts accordingly, for example by marking the item or the list as dirty before actually setting the real value.
Edit: Alternatively, are there generic setters (like in PHP 5) in Java, that is, a method that gets called if a property doesn't exist? Or is there a type of object that I can add properties to at runtime?
If with "properties" you mean JavaBean properties, i.e. represented bay a getter and/or a setter method, then you can use a dynamic proxy to intercept the set method.
If you mean instance variables, then no can do - not on the Java level. Perhaps something could be done by manipulations on the byte code level though.
Actually, the easiest way to do it is probably by using AspectJ and defining a set() pointcut (which will intercept the field access on the byte code level).
The design pattern you are looking for is: Differential Execution. I do believe.
How does differential execution work?
Is a question I answered that deals with this.
However, may I suggest that you use a callback instead? You will have to read about this, but the general idea is that you can implement interfaces (often called listeners) that active upon "something interesting" happening. Such as having a data structure be changed.
Obligitory links:
Wiki Differential execution
Wiki Callback
Alright, here is the answer as I see it. Differential Execution is O(N) time. This is really reasonable, but if that doesn't work for ya Callbacks will. Callbacks basically work by passing a method by parameter to your class that is changing the array. This method will take the value changed and the location of the item, pass it back by parameter to the "storage class" and change the value approipriately. So, yes, you have to back each change with a method call.
I realize now this is not what you want. What it appears that you want is a way that you can supply some kind of listener on each variable in an array that would be called when that item is changed. The listener would then change the corresponding array in your "backup" to refect this change.
Natively I can't think of a way to do this. You can, of course, create your own listeners and events, using an interface. This is basically the same idea as the callbacks, though nicer to look at.
Then there is reflection... Java has reflection, and I am positive you can write something using it to do this. However, reflection is notoriously slow. Not to mention a pain to code (in my opinion).
Hope that helps...
I don't want to intercept method calls before they are invoked on the real object, but
rather I'd like to intercept properties that are being changed
So in fact, the objects you want to monitor are no convenient beans but a resurgence of C structs. The only way that comes to my mind to do that is with the Field Access call in JVMTI.
I wanted to do the same thing myself. My solution was to use dynamic proxy wrappers using Javassist. I would generate a class that implements the same interface as the class of my target object, wrap my proxy class around original class, and delegate all method calls on proxy to the original, except setters which would also fire the PropertyChangeEvent.
Anyway I posted the full explanation and the code on my blog here:
http://clockwork-fig.blogspot.com/2010/11/javabean-property-change-listener-with.html

Categories

Resources