Let callables/threads work on copy of an object in Java - java

I have a working code, in which I calculate the shortest path from every point (Dijkstra's algorithm) to every point in a graph.
But as soon as I want to use more than 1 thread with my ExecuterService, they all will work on the same graph for calculating the results, which of course makes the result unusable.
How can I make it so that one thread gets an own copy of the graph, so the callables run on that thread won't disturb the others? Is that even possible?

As Keqiang Li commented, you need to define a mechanism for copying the single graph data structure you already have. However, since you obviously need to first build the structure itself before creating multiple copies of it, one commonly-used trick is to use a builder pattern in order to create immutable objects on which you will actually do the search. Note that this needn't be implemented in an actual separate e.g. GraphBuilder class but rather you can simply implement a mechanism for creating immutable copies of a single mutable graph structure which you initially build incrementally while reading in your data:
public class MutableDirectedGraph implements DirectedGraph {
public MutableDirectedGraph() {
...
}
public Edge addEdge(final Node start, final Node end, final String label, final double weight) {
...
}
public Node addNode() {
...
}
...
}
public class ImmutableDirectedGraph implements DirectedGraph {
public ImmutableDirectedGraph(final DirectedGraph copyee) {
...
}
...
}
One nice thing about this approach is that you can implement MutableDirectedGraph to be easy to modify/build in an incremental fashion and then implement ImmutableDirectedGraph with optimizations for searching (e.g. storing Edge objects by their respective IDs in an array for memory-efficient storage while using Map-based storage in the mutable version). In this way, making two separate classes for two specific tasks may be quicker for the programmer as well as for the computer to deal with.

Related

Am I violating the "open/closed" principle?

Scenario: I stored some information (e.g. an array of doubles) in a class field (say field Measurements, array of integers in a class MeasureData). Now I would like to use this data to perform some calculations (e.g compute the arithmetic mean of the array, the maximum and the minimum). At the moment, I don't know if in the future I'll need to do any other operation on those data (e.g. maybe I will need to get the standard deviation, the sum or whatever). I'll have many objects of type MeasureData.
Solution: I could write a class Calculator, declare it final, use a private constructor and use several static methods to perform the calculations I need. This seems to make sense, since Calculator acts as an utility class, without any field, much like the standard Math class.
Problem: if, in a couple of months, I'll need to do any other calculation, I'll be needing to write another static method in Calculator. Does this mean to violate the open/closed principle (after all, I'm modifying the implementation of the class Calculator)?
The strict answer is yes; OCP states that a class is open for extension but closed for modification. You would be modifying Calculator, and, hence, violating OCP (as you've already concluded).
This leads to two points:
First, is violating OCP a big deal in this case? You're additively changing Calculator to add a new method to it. Calculator is a static helper class used to get meaningful data from your objects. Adding a new method, like calculating SD, is not going to affect any of the other operations within it. With a proper implementation, is there really a way that adding this method could compromise your project?
Second, if you feel like the OCP violation is not acceptable, then this is a textbook example of where Strategy Pattern can be utilized. Consider:
Measurements.Java
public class Measurements {
private int[] data;
public Measurements(int[] data) {
this.data = data;
}
public Number performCalculation(Calculation c) {
return c.performCalculation(data);
}
}
Calculation.java
public interface Calculation {
Number performCalculation(int[] data);
}
You can then make a calculation class for each different calculation you want to do on the data (eg: MeanCalculation, StdDevCalculation, etc.). If you want a new calculation (eg: MedianCalculation), you can make this without modifying any of the other code in this area (closed for modification, open for extension; OCP compliant). The end result looks like:
Measurements values = ...
Number mean = values.performCalculation(new MeanCalculation());
Number SD = values.performCalculation(new StdDevCalculation());
// etc.
I'm not saying this is the best approach (or best implementation of the approach even) for your specific case; you need to answer that for yourself. But I hope this answer provides a decent external perspective on the matter.

How can I reuse collections that would use the same backing iterator?

I'm fairly new to Java so my knowledge is pretty limited. I'm working on a personal project where I'm trying out some of the techniques used in Guava for creating views/transformations of collections. I made a class called View to take an inputted collection as the backing iterable, and a transformation, and then present it as a read-only iterable. (not a collection, though I don't think it makes much of a difference for this question). Here is a quick example of using it...
public class Node {
public enum Change implements Function<Node, Coordinate> {
TO_COORDINATE;
#Override public Coordinate apply(Node node) {
return new Coordinate(node);
}
}
private HashSet<Node> neighborNodes = new HashSet<Node>();
//various other members
public View<Coordinate> viewNeighborCoordinates() {
return new View<Coordinate>(neighborNodes, Change.TO_COORDINATE);
}
}
now if some method wants to use viewNeighborCoordinates() of this node, and then later some other method also wants to viewNeighborCoordinates() of this node, it seems wasteful to always be returning new objects, right? I mean any number of things should be able to share reference to a view of the same backing iterable with the same transformation, since all they're doing is reading through it. Is there an established way of managing a shared pool of objects which can be "interned" like Strings are? Is it just having to make some sort of ViewFactory that stores a running list of views in use, and everytime someone wants a view, it checks to see if it already has that view and hands it out? (is that even more efficient)?
As already stated, interning is possible (look at Interners), but most probably a bad idea.
Another possibility is lazy initialization of a field storing the View. Since I'm lazy as well, I only point you to a Lombok implementation. Be careful with DCL, if you want to try this. In case your class is immutable, you may need no synchronization at all, like e.g. String.hashCode.
A very simple possibility is eager initialization of a field. Assuming you need the view often, it's the best way.
But without knowing more, your current implementation is best. Beware the root of all evil.
Don't optimize without profiling or benchmarking (and if you benchmark, then do it right, i.e., using caliper or jmh. Home-baked benchmarking in Java just doesn't work).

Graph Theory Program

So right now i'm in a class learning graph theory. I thought it would be cool to make a program for it. To create different graphs, add and deleted nodes, edges and all the sort like that.
This semester I do not have no programming classes, so I'm trying to get ready for next semester when they start up again.
So far what I have is a Class called Graph Theory (Driver/Command-line) which of course runs the whole program.
Besides the driver class the main classes I have are:
--Graph: TYPES: Path, Cycle, Complete...
Because they all have lists of nodes and edges and add/deleted methods in common I made the TYPES, like path and cycle, inherit from graph so I didn't have to remake those million methods for each one.
In the driver class I have a list of all created graphs.
ArrayList<Graph> graphs = new ArrayList<Graph>();
My problem is when I started working on the Partite graph class it inherits from Graph like the others, but I can't access the methods.
I the driver when i create the Partite:
Partite p = new Partite(blah, blah);
graphs.add(p);
When I go through and get this graph from the list I can't access the methods from Partite.
How can I do this.
Because when you get elements from graphs they will be references of type Graph.
To access the methods from Partite you must add a cast to Partite.
Partite p = new Partite(blah, blah);
graphs.add(p);
Partite other = (Partite)graphs.get(0);
other.methodFromPartite();
Done.
Basic solution
If you rely on specific Partite methods (as opposed to Partite's versions of Graph's methods) you shouldn't really be holding it in an array of Graphs but if you must you can cast
Graph g=graphs.get(i);
Partite p=(Partite)g;
Be aware that if you get it wrong (attempt to cast something that isn't a Partite) you will get an exception. You can check in advance if the cast is acceptable by using instanceof
if (g instanceof Partite){
.....
}
A better concept
But as I say all this is usually a sign of bad program design. A better design would be to have only general graph behaviour triggered from reading this list (Partites would still be in the list, but they would behave as Graphs) and a seperate list of Partites being held as well for whatever different behaviour they need
An even better concept
If you can organise your program in such a way that you are only calling methods from Graph but Parties overrides some of them such that it behaves the way you want that is the ideal solution.
For example Graph has update and Partites` overrides update to do the extra work it needs as well. So
public class Graph {
public void update(){
doImportantWork();
}
}
public class Partite extends Graph{
#Override
public void update() {
super.update(); //so that the basic graph behavior happens
doPartiteSpecificImportantWork();
}
}
This is not always practical however.
This is probably because you're trying to modify your Partite object using a Graph reference to it. If you want to call sub class specific methods using parent class references, your design probably needs some modification (this is a code smell). To temporarily get around it for now you can case your Graph reference to a Partite reference.
((Partite)graphRef).[some method on partite]

Best pattern to update an object each iteration of an algorithm

I have an algorithm that alters the state of an object each generation, depending on some semi-random modifications made to a list. I made a simplification to be clearer, so assume I have two class:
public class Archive{
...
}
public class Operation{
...
}
In another class,Algorithm, a method iterates, make some adjustments to a List<Operation> (similar to Genetic Algorithm crossovers and mutations). This list among with other objects related are used to update an Archiveobject, making a lot of calculations and modifications to the Archive object.
In the current version of my code I have a ArchiveUpdateclass that has a internal Archive object and a method that receives ALL the objects used in the update to change the Archive. I think this way is kinda fuzzy and I can't think of another way of doing this better, can anybody help?
Have you considered making the Archive immutable and providing methods that return new Archive instances based on an existing archive? That is, something like:
public class Archive {
private final String field;
public Archive(String field) { this.field = field; }
public Archive changeField(String newField) { return new Archive(newField); }
}
If your objects are all immutable, it's much easier to reason about their state and you wouldn't need an ArchiveUpdate class. However, without more examples of exactly how these classes get used I can't suggest much else.
Its hard to grasp completely...but from what I understood you need a pattern that would allow you to be notified if a "monitored" state changed. If that is the case you should look at Observer pattern it provides a simple way of monitoring state changes.

"Leaking this" from a Design Standpoint

Warning: Leaking "this" in constructor
I keep running into this, and I have a nagging feeling that it's because my design is wrong or not optimal.
I understand that this warning is bringing to my attention the fact that I am allowing access to an object that is potentially not fully initialized.
Let's say that I need a Frame that HAS and requires a List (Frame(List list)). In List, I might want to do something such as add(). In order to make sure Frame knows as little about List as possible (only that it has one), I would want to access the containing Frame from the List (List HAS a Frame?). This seems a little silly, but I have 2+ implementations of List that will use Frame in different ways..
To ensure that my code is used properly, I would require a Frame in the constructor of List.
I would also require a List in the constructor of Frame, as it MUST have one:
public abstract class Frame {
private final List list;
public Frame(List list) {
this.list = list;
list.setFrame(this);
}
}
public abstract class List {
private Frame frame;
protected final void setFrame(Frame frame) {
this.frame = frame;
}
}
So, is this bad design, or should I really create some intermediate scaffolding that does this, or even leave the scaffolding to the user?
Thanks!
Introduce a factory method:
public static Frame createFrame(List list) {
Frame frame = new Frame(list);
list.setFrame(frame);
}
private Frame(List list) {
this.list = list;
}
This does not leak this, and always makes sure everything is configured correctly without the need for every caller to remember initializing both sides of the association.
I think that this sort of "doubly linked" structure, where a Frame points to a List that points back to its parent Frame, is something you ought to avoid unless you have a specific need for it. You should if possible try and make one of the two objects the "parent" that points to the "child."
It's a bit hard to understand at first why the double-linking is not such a great idea, but here are some reasons:
In a structure with clear parent-child relationships, it's trivial to reuse the same child objects in more than one parent. In a double-linked structure, on the other hand, if you want to create a new structure that shares some of the elements from an original, you either have to create new copies of the elements of interest, or you have to destroy the original structure.
There are many design patterns that rely on a clear chain of "command" in an object graph, and the double-linked structures obscure that chain of command from readers of the code.
A lot of the cases where processing of a child requires knowledge about the parent in which that child appears are better handled by passing the parent as a "context" argument to a method that processes the child. The classic example of this pattern is in interpreters, where evaluation of an expression takes as an argument an "environment" that contains all the of the outside information necessary to evaluate a child expression. (Or alternatively, you use a stateful Iterator or Hierarchical Visitor that navigates the structure and keeps track of location.)
This is not to say that the double-linked structures are never appropriate, but rather that the simpler, single-linked structures should probably be the first choice.

Categories

Resources