Object without a value - java

I was asking this question about controlling a thread that was reading from a blocking queue. Although it wasn't the solution I chose to go with, several people suggested that a special "poison pill" or "sentinel" value be added to the queue to shut it down like so:
public class MyThread extends Thread{
private static final Foo STOP = new Foo();
private BlockingQueue<Foo> blockingQueue = new LinkedBlockingQueue<Foo>();
public void run(){
try{
Foo f = blockingQueue.take();
while(f != STOP){
doSomethingWith(f);
f = blockingQueue.take();
}
}
catch(InterruptedException e){
}
}
public void addToQueue(Foo f) throws InterruptedException{
blockingQueue.put(f);
}
public void stop() throws InterruptedException{
blockingQueue.put(STOP);
}
}
While I like this approach, I decided not to use it because I wasn't sure what value to use for the STOP field. In some situations it's obvious - for instance, if you know you're inserting positive integers, negative numbers could be used as control values - but Foo is a fairly complex class. It's immutable and hence has a constructor that takes several arguments. To add a no-argument constructor would mean leaving several fields uninitialised or null, which would cause methods to break if they were used elsewhere - Foo is not just used with MyThread. Similarly, putting dummy values into the main constructor would just pass this problem on as several of the fields and constructor parameters are themselves significant objects.
Am I simply programming over-defensively? Should I worry about adding no-argument constructors to a class, even if there are no setters to make the object usable (just assume other programmers will be sensible enough to not use that constructor)? Is the design of Foo broken if it can't have a no-argument constructor or at least a non-value - would it be better to put if(someField == null){throw new RuntimeException();} checks in all methods?

I don't really see what the advantage of this design is versus a simple boolean variable to indicate the loop should stop.
But if you really want to go with this design, I would suggest making a private no-arg constructor, and making a static STOP Foo. Like this.
public class Foo {
public static final Foo STOP = new Foo();
... fields
private Foo(){}
public Foo(...){
...
}
...
}
public class MyThread extends Thread{
private static final Foo STOP = new Foo();
private BlockingQueue<Foo> blockingQueue = new LinkedBlockingQueue<Foo>();
public void run(){
try{
Foo f = blockingQueue.take();
while(f != STOP){
doSomethingWith(f);
f = blockingQueue.take();
}
}
catch(InterruptedException e){
}
}
public void addToQueue(Foo f) throws InterruptedException{
blockingQueue.put(f);
}
public void stop() throws InterruptedException{
blockingQueue.put(Foo.STOP);
}
}
This has the advantage that you're still not exposing an invalid constructor.
The disadvantage is that the Foo class knows that in some cases it's used as a 'poison pill', which might not be what it's for. Another disadvantage is that The STOP object might be inconsistent. You could make an anonymous subclass from it do disable the methods with UnsupportedOperationException or something.

I think you're right about not using empty constructors. If Foo is such an complex class, it doesn't seem logical to use a complete object for that.
If adding a null is possible. That seems a nice way to go.
Another way could also be to implement an interface. IBlockableQueueObject? This could be implemented by the foo object and by the STOP sign. Only thing is that you have to cast the interface back to the Foo if it is not a STOP.

another option would be to wrap Foo in a generic wrapper such as this:
public class Wrapped<T> {
private final T value;
public Wrapped(T value) {
this.value = value;
}
public T get() { return value; }
}
which you can then use to pass a null value as a poison pill to a BlockingQueue<Wrapped<Foo>>.

You should worry about having no-argument constructors that don't result in usable instances.
The design of Foo sounds fine - I would generally assume that I'm not allowed to pass in null into a constructor unless the documentation specifically allows me to. Especially with an immutable class.

Related

Call method once after any one of a few overloaded methods are called

In an abstract class I have a Predicate field, that is meant to be a combination of an unknown number of other Predicates. Joining the predicates works just fine but I am trying to have some way to know when the predicate has been initialized (or rather, just a way to know if it has or hasn't been initted).
Here is a short example of what I'm talking about:
public abstract class LimitedSystem implements Moveable {
private Predicate<Double> limits;
private final boolean initialized;
public void setLimits(SingleLimit... limits) {
List<Predicate<Double>> limitsList = Arrays.asList(limits);
this.limits = limitsList.stream().reduce(Predicate::and).orElse(x -> true);
}
public void setLimits(TwoLimits limits) {
this.limits = limits;
}
...
I am looking for ways to set initialized to true once (and once only, hence the final. I think I used it right) any of the setLimits have been called (they're overloaded).
I have other setLimits methods, but for the sake of generic code, I don't want to put a initialized at the end of each of the overloaded methods.
So my question is how can I, in a generic way, set the value of initialized after any of the setLimits methods has been called.
My first idea was to try to wrap the setLimits in some generic method which would call the correct overload by the parameter it gets, and then change initialized in that method. But I am not sure if that's a good idea.
Some other idea I got from another question1 was to put the setLimits in some interface or something similar. But I'm not sure how useful that might prove.
So how might this be accomplished?
(Also, if you happen to notice any design problems in this, please tell me because I'm trying to improve in that matter)
There's no need for separate fields:
private Predicate<Double> limits;
private final boolean initialized;
is basically
private Optional<Predicate<Double>> limits = Optional.empty();
if you want initialized to be set to true once limits is set,
provided you can guarantee that none of the setLimits methods can set it to Optional.empty() again. initialized == limits.isPresent().
You can't guarantee that a method is called in the body of an overridden method; in any case, this is a variant of the Call super antipattern.
You can do it like this:
abstract class Base {
final void setFoo(Object param) { // final, so can't be overridden.
setFooImpl(param);
thingThatMustBeCalled();
}
protected abstract void setFooImpl(Object param);
final void thingThatMustBeCalled() { ... }
}
class Derived extends Base {
#Override protected void setFooImpl(Object param) { ... }
}
But it's pretty ugly.

Dealing with final fields when overriding clone

I'm writing a class in which I have to override the clone() method with the infamous "super.clone() strategy" (it's not my choice).
My code looks like this:
#Override
public myInterface clone()
{
myClass x;
try
{
x = (myClass) super.clone();
x.row = this.row;
x.col = this.col;
x.color = this.color;
//color is a final variable, here's the error
}
catch(Exception e)
{
//not doing anything but there has to be the catch block
//because of Cloneable issues
}
return x;
}
Everything would be fine, except that I can't initialize color without using a constructor, being it a final variable... is there some way to both use super.clone() AND copying final variables?
Since the call to super.clone(); will already create a (shallow) copy of all the fields, final or not, your full method will become:
#Override
public MyInterface clone() throws CloneNotSupportedException {
return (MyInterface)super.clone();
}
This requires that the superclass also implements clone() properly (to ensure that the super.clone() eventually reaches the Object class. All the fields will be copied properly (including final ones), and if you don't require deep clones or any other special functionality, you can use this and then promise that you'll never try to implement clone() again (one of the reasons being that it's not easy to implement it correctly, as evident from this question).
Under the assumption that you don't have another choice you can use Reflection. The following code shows how this forks for the field color.
You need some try-catch around it.
Field f = getClass().getDeclaredField("color");
f.setAccessible(true);
f.set(x, this.color)
One thing to keep being mindful of, when mixing clone and final fields, especially the one with initializers, is that (as one of the comments rightfully says), the values are copied from the original, no matter whether that field is final or not, and initializer be damned.
So if a final field has a dynamic initializer, it's actually not executed. Which, IMHO, is breaking a serious expectation that if I have a final instance field in a class, every new instance of this class is going to initialize the field to whatever value the initializer says it should be.
Here is an example where this can be a (insert your level of seriousness) problem:
import lombok.SneakyThrows;
import java.util.HashMap;
import java.util.Map;
public class App {
public static void main(String[] a) {
Cloned c1 = new Cloned();
c1.d.put("x", "x");
Cloned c2 = c1.clone();
System.out.println("c2.x="+c2.d.get("x"));
c1.d.clear();
System.out.println("c2.x="+c2.d.get("x"));
}
static class Cloned implements Cloneable {
public final Map<String, String> d = new HashMap<>();
#Override
#SneakyThrows
public Cloned clone() {
return (Cloned) super.clone();
}
}
}
Output:
c2.x=x
c2.x=null

Java - Class type from inside static initialization block

Is it possible to get the class type from inside the static initialization block?
This is a simplified version of what I currently have::
class Person extends SuperClass {
String firstName;
static{
// This function is on the "SuperClass":
// I'd for this function to be able to get "Person.class" without me
// having to explicitly type it in but "this.class" does not work in
// a static context.
doSomeReflectionStuff(Person.class); // IN "SuperClass"
}
}
This is closer to what I am doing, which is to initialize a data structure that holds information about the object and its annotations, etc... Perhaps I am using the wrong pattern?
public abstract SuperClass{
static void doSomeReflectionStuff( Class<?> classType, List<FieldData> fieldDataList ){
Field[] fields = classType.getDeclaredFields();
for( Field field : fields ){
// Initialize fieldDataList
}
}
}
public abstract class Person {
#SomeAnnotation
String firstName;
// Holds information on each of the fields, I used a Map<String, FieldData>
// in my actual implementation to map strings to the field information, but that
// seemed a little wordy for this example
static List<FieldData> fieldDataList = new List<FieldData>();
static{
// Again, it seems dangerous to have to type in the "Person.class"
// (or Address.class, PhoneNumber.class, etc...) every time.
// Ideally, I'd liken to eliminate all this code from the Sub class
// since now I have to copy and paste it into each Sub class.
doSomeReflectionStuff(Person.class, fieldDataList);
}
}
Edit
I picked the accepted answer based on what applied best to my problem, however it seems to me that all three of the current answers have their merits.
No, it's not possible without grabbing the stacktrace (which is imo nastier than your initial approach and for which I would in any way prefer Thread#getStackTrace() above new Exception()).
Rather do that job in a non-static initializer (or the default constructor) of the abstract class where you check the initialized status.
public abstract class SuperClass {
{
if (!isInitialized(getClass())) {
initialize(getClass());
}
}
}
The called methods in turn can be safely static.
yes, I use this often to initialize a static Log variable :
e.g. :
public class Project implements Serializable, Cloneable, Comparable<Project> {
private static final Logger LOG = LoggerFactory.getLogger(Project.class);
...
To get a class at runtime, you could do something along the lines of
public class Test {
public static void main(String[] args) {
try{
throw new Exception();
}
catch(Exception e){
StackTraceElement[] sTrace = e.getStackTrace();
// sTrace[0] will be always there
String className = sTrace[0].getClassName();
System.out.println(className);
}
}
}
Not pretty but will do the job (ripped from http://www.artima.com/forums/flat.jsp?forum=1&thread=155230).
This means you still make a call from the subclass (so is in the stack trace), but you don't need to include the XXX.class as an argument.

How can I know whether an instance of a class already exists in memory?

How can I know whether an instance of a class already exists in memory?
My problem is that don't want read method if exist instance of Class
this is my code
private void jButton (java.awt.event.ActionEvent evt) {
PNLSpcMaster pnlSpc = new PNLSpcMaster();
jtabbedPanel.addTab("reg",pnlSpc);
}
I want check instance of PNLSpcMaster of course I can check by static boolean but I think this way is better.
If you want to have only one instance of "PNLSpcMaster" then you do need a singleton:
This is the common singleton idiom:
public class PNLSpcMaster {
/**
* This class attribute will be the only "instance" of this class
* It is private so none can reach it directly.
* And is "static" so it does not need "instances"
*/
private static PNLSpcMaster instance;
/**
* Constructor make private, to enforce the non-instantiation of the
* class. So an invocation to: new PNLSpcMaster() outside of this class
* won't be allowed.
*/
private PNLSpcMaster(){} // avoid instantiation.
/**
* This class method returns the "only" instance available for this class
* If the instance is still null, it gets instantiated.
* Being a class method you can call it from anywhere and it will
* always return the same instance.
*/
public static PNLSpcMaster getInstance() {
if( instance == null ) {
instance = new PNLSpcMaster();
}
return instance;
}
....
}
Usage:
private void jButton (java.awt.event.ActionEvent evt) {
// You'll get the "only" instance.
PNLSpcMaster pnlSpc = PNLSpcMaster.getInstace(); //<-- getInstance()
jtabbedPanel.addTab("reg",pnlSpc);
}
Or directly:
private void jButton (java.awt.event.ActionEvent evt) {
jtabbedPanel.addTab("reg",PNLSpcMaster.getInstace());
}
For basic usages the Singleton Pattern works very well. However for more sophisticated usages it may be dangerous.
You could read more about it: Why singletons are controversial
I think you're after the singleton pattern.
Several factors would contribute to obtaining a reliable solution in Java, as opposed to C++.
The following example is unreliable, although it could provide you with a correct enough answer if you use the hasAtleastOne() method.
class Example {
private static int noOfInstances = 0;
public Example() {
noOfInstances++;
}
public static boolean hasAtleastOne() {
if(noOfInstances > 0)
return true;
else
return false;
}
protected void finalize() throws Throwable {
noOfInstances--;
}
}
The unreliability stems out of the fact that destructors are not available in Java, unlike C++. It is upto the garbage collector to release the memory consumed by an instance - the instance could still be floating in memory as an orphan since no other object references it. Hence, you never know whether an object is no longer being referenced.
Admittedly, that is theoretically different from being absent in memory at all, but you will have to wait for the finalize() method to be called before you know for sure that no such instance of the class is available. Finalizers come with a warning - they are not to be relied upon in time-critical applications, since it could be a factor of a few seconds to minutes between object orphaning and finalization; in short there is no guarantee that they could be called.
The Dispose Pattern
You could add more reliability to the solution by implementing the Dispose pattern. This also requires the client of the class to invoke the dispose method to signal that the instance is to be disposed off, so that the instance count can be reduced. Poorly written clients will make the solution unreliable.
There isn't a reasonable way to find out whether or not an instance of a particular class already exists.
If you need to know this information, create a static boolean field and set it from the constructor:
class MyClass {
private static bool instanceExists = false;
public MyClass() {
MyClass.instanceExists = true;
}
}
For classes that have a notion of identity, the Identity Map pattern applies.

java thread safe code + an atomic method question

I have a class Manager that is going to be accessed by multiple threads at the same time, I want to know if I did it the right way ?
also I think I need RemoveFoo to be atomic, but I'm not sure
public class Manager
{
private ConcurrentHashMap<String, Foo> foos;
//init in constructor
public RemoveFoo(String name)
{
Foo foo = foos.Get(name);
foo.RemoveAll();
foos.Remove(name);
}
public AddFoo(Foo foo)
{...}
}
public class Foo
{
private Map<String,Bar> bars;
//intialize it in constructor
//same for RemoveBar
public void AddBar(Bar bar)
{
synchronized(this)
{
bars.put(bar.id, bar);
}
}
public void RemoveAll()
{
synchronized(this)
{
//some before removall logic for each one
bars.remove(bar.id, bar);
}
}
}
public class Bar
{}
You do not need synchronised methods as you are using a ConcurrentHashMap, however be aware that Foo foo = foos.Get(name) could return null as another thread could already have removed the entry from the map.
Members can be declared as Map<String, Foo> foos, but must be initialsed as foos = new ConcurrentHashMap<String, Foo>;
RemoveFoo could be problematic. I suggest to use:
Foo foo = foos.remove (name);
if (foo != null) foo.removeAll();
instead. This makes sure that the map doesn't change between get() and remove().
In Foo, it's enough to synchronize on bars instead of the whole instance. But that's just a minor optimization.
Declare RemoveFoo(String) as synchronized:
public synchronized void RemoveFoo(String name) {
…
}
Also, be advised of the following:
method names should be lower case, e.g. removeFoo instead of RemoveFoo. This is not C#. :)
Every method needs a return type: public removeFoo() is not a valid method declaration, it needs to be public void removeFoo().
If you use a concurrentHashMap in Foo like
private Map<String,Bar> bars = new ConcurrentHashMap<String, Bar>();
maybe you can do away with the synchronization in Foo as well.
I am not sure what you are going to do on Foo and Bar, but it looks like a pattern of deallocation.
If they are not referenced by others, just call foos.Remove(name); and let GC engine handle the deallocation.

Categories

Resources