Destroying multiple references to the same object in Java - java

Say I have a Citizen class and a Population class. A population contains a set of citizens.
In this simulation, citizens may die. Currently, to represent the death of a citizen, I destroy all references to that citizen object, as a Population may not contain a dead citizen.
I want to be able to create multiple Population objects where citizen overlap is possible. Ex. Citizen C may belong to both Population A and Population B. However, this makes citizen deaths difficult as I would have to remove citizen C from both A and B on the event of a death. Sometimes A and B aren't even in the same scope.
Also, each citizen must belong to at least one population.
Generally speaking, how would I organize my Population and Citizen class to ensure that a citizen is completely removed from all instances of Population upon that citizen's death?
I'm thinking of making Citizen a member class of Population, but I do not know where to go from there.
Thanks.

If you think of it as a real life scenario, if a citizen belongs to few populations, then in case of death those populations need to be informed (lets say, if he is French and American, both countries need to know that to cancel his passport etc.). So the observer pattern here, as #nablex suggested, sounds like the most appropriate solution.
Have a class, like 'MinistryOfDeath' or something, that will inform the relevant populations.

There are a number of solutions to this problem like observer pattern etc but if having a reverse link from citizen to population is already considered too heavy, any solution in that direction is probably too heavy weight.
If you really don't want a reverse link (though probably the best option and memory probably won't suffer that badly), you can always have an isDead() on the citizen.
Any population must then either periodically or upon access prune the dead citizens.

When compared to List<Population, an int[] with numbering all the populations would save half the memory only on machines with above something like 32 GB, where compressed OOPs don't get suffice, otherwise nothing.
Using a short[] saves half the memory when compared to int[]. Using a BitSet saves much more. You could even run your own, e.g., 2 longs for a fixed set of 128 populations and use only 16 bytes per Citizen. This is much much cheaper than the forward links from Populations to Citizens.

Related

If classes all contain lots of useful class variables, will it have an impact on performances?

Whenever I write a new class, I use quite a ton of class variables to describe the class's properties, up to the point where when I go back to review the codes I've typed, I see 40s to 50s of class variables, regardless of whether they are public, protected, or private, they are all used prominently throughout the classes I've defined.
Even though, the class variables consists of mostly primitive variables, like booleans, integers, doubles, etc., I still have this uneasy feeling where that some of my classes with large amounts of class variables may have an impact on performances, however negligible they may be.
But being rational as possible, if I consider unlimited RAM size and unlimited Java class variables, a Java class may be an infinitely large block of memory in the RAM, which the first portion of the block contains the class variables partitions, and the rest of the block contains the addresses to the class methods within the Java class. With this amount of RAM, the performance for it is very nontrivial.
But that above isn't making my feelings any easier than said. If we were to consider limited RAM but unlimited Java class variables, what would be the result? What would really happen in an environment where performance matters?
And probably may get mentioned beforehand, I don't know if having lots of class variables counts as bad Java practice, when all of them are important, and all classes have been refactored.
Thanks in advance.
Performance has nothing to do with the number of fields an object has. Memory consumption is of course potentially affected, but if the variables are needed, you can't do much about it.
Don't worry too much about performance. Make your code simple, readable, maintainable, tested. Then, if you notice performance problems, measure and profile to see where they come from, and optimize where needed.
Maintainability and readability is affected by the number of fields an object has though. 40 to 50 fields is quite a lot of fields, and is probably an indication that your classes do too much on their own, and have too many responsibilities. Refactoring them to many, smaller subclasses, and using composition would probably be a good idea.
I hope I don't sound like an ass, but in my view having more than 10 properties in a class is usually a hint of a bad design and requires justification.
Performance wise, if you very often need all those properties, then you're going to be saving some memory, as each object also has a header. So intead of having 5-10 classes you put everyting into one and you save some bytes.
Depending on which garbage collector you use, having bigger objects can be more expensive to allocate (this is true for the CMS garbage collector, but not for the parallel one). More GC work = less time for your app to run.
Unless you're writing a high traffic, low latency application, the benefits of having less classes (and using less memory) is going to be completely overwhelmed by the extra effort needed for maintenance.
The biggest problem I see in having a class with a lot of variables is Thread safety - it is going to be really hard to reason about the invariants in such a case. Also reading/maintaining such a class is going to be really hard.
Of course if you make as much as you can fields immutable, that is going to be a lot better.
I try to go with : less is better, easier to maintain.
A basic principle we are always taught is to keep cohesion high (one class is focusing on one task) and coupling low (less interdependency among classes so that changes in one doesnot effect others).
While designing a system, I will believe the focus should be more on maintainable design, performance will take care of itself. I don't think there is fixed limit on number of variables a class can have as a good practice, as this will strictly depend on your requirement.
For example, if I have a requirement where the application suggest a course to student, and algorithm needs 50 inputs (scores, hobbies etc), it will not matter whether this data is available in one class or multiple, as the whole information needs to be loaded in the RAM for a faster execution.
I will again say, take care of your design, it is both harmful to keep unnecessary variables in a class (as it will load non-required information to RAM) or split into more classes than required (more references and hence pointer movement)
1. I always use this as a thumb of rule. A Class should have only One reason to Change, so It should Do only One Thing.
2. Keeping this in mind i take those variables which are needed to define this class's attributes.
3. I make sure that my class is following the Cohesive principle, where the Methods within the class reflects the Class name.
4. Now after sorting everything out, if i need some other variables to work-out my class, then i need to use them, i have no choice...Moreover after all these thinking and work going into creating a class, will be hardly effected by some additional variables.
Sometimes class variables are used as static final constants to store some default strings like product name, version, OS version, etc. Or even to store product specific settings like font size, type, etc. Those static variables can be kept at class level.
You can also use HashMap instead of simple class if you just want to store fields constants or like product setting that rarely change. That may help you speed you response time.
Two things I would like to mention :
1. All instance variables are stored in Heap area of RAM..
2. All static variables are stored in non Heap area(Method area to be specific).
Whatever be the type of variable(instance or static), ultimately all reside in RAM.
Now coming to your question. As far as instance variable is concerned, java's built-in Garbage collector will work, in most cases well and truly effectively, to keep freeing memory. However, static variables are not garbage collected.
If you are highly concerned with memory issues due to large number of variables in your class, you can resort to using Weak References instead of traditional strong reference.

How to decrease java program's memory consumption

I have a Java 3D program which uses lots (hundreds) of 3D models (3ds and obj).
The more models I use (and I really, really have to, it's kind of 3D model of the real world object) the more heavier the program becomes, till the point when any single operation takes ages to complete.
CPU consumption rarely reaches 50%, mostly is moving between 10%-30%, but memory consumption is growing (obviously) with each added 3D model.
I know how to minimize memory imprint of c++/ c programs, but with Java's GC is there anything I can do about it except increasing the JVM's memory with -Xmx? I am already running with -xMx512Mb.
I have checked GC logs, using GCViewer, didn't find anything suspicious.
I am aware of some very similar questions on SO, but none answered my question exactly.
My IDE is IntelliJ 11.
There are two simple ways to decrease the number of objects you are creating, and one or both of them may work for your purposes, though without specifications I can't be sure.
1) Work with highly mutable objects. If you need to simulate a large number of things with a great deal of similarity, but which don't have to interact with each other (for example, a hundred thousand simulations of a dozen particles interacting, with slightly different particles each time), then using the same dozen or so objects over and over, and making use of mutator functions to transfer the burden to the CPU. However, I doubt that using many objects in sequence is a problem for you, given that Java already has built-in garbage collection.
2) Make the similarities between similar objects their own class. For example, if you have the need for a lot of objects, and you notice that a significant proportion of them share a number of memory-intensive characteristics, store those characteristics in their own class and refer to a single instance of that class in every object with the exact same field values. As an example, consider a set of Apple objects. You could either create different classes for GrannySmithApples, MackintoshApples, RedDeliciousApples with their own static fields for characteristics shared across the class (e.g. RedDeliciousApples have a static String field declared in the abstract class Apple and set to "red"), or (to allow more flexibility at runtime) each class could have an instance of CoreCharacteristic. If multiple objects share the same core characteristics, the code:
CoreCharacteristic c = new CoreCharacteristic(<some parameters>);
Apple apple1 = new Apple(c);
Apple apple2 = new Apple(c);
Apple apple3 = new Apple(c);
Apple apple4 = new Apple(c);
will use only one CoreCharacteristic for all four apples, quartering the amount of memory needed to store the fields of CoreCharacteristic which would have otherwise been replicated for each Apple.
There are two different approaches I can think of to handle your issues:
Control when the GC kicks in: here is a full article describing how to control the garbage collector and the different algorithms used to clean up the memory. I found this approach very useful when an application is creating thousands and thousands of DTOs in a minute.
If your application is not creating too many objects that are trashed quickly then I suggest you have a look at your model and improve its efficiency. Remember that when dealing with 3D visualization, all what matters is how you structure your scene graph.
On a side note, 3D visualization does not take that much CPU when using OpenGL based solutions. This is mainly due to the fact that it is the GPU that gets involved a lot when rendering the scene graph, not the CPU.
From my point of view you have two options:
decrease creating new objects by making them immutable, and reuse of them if they not vary
use flywieght pattern - reuse created objects and work with setters on them, in place of creating new ones again and again - here is great example of implementation that may exaclty suit your needs http://www.javacamp.org/designPattern/flyweight.html - it's about creating color circles. Without flywieght it took 2,5x longer, and memory consumption was ~200 larger. Try it.

Inheritance/Interface design of a game

I'm designing a game, but I can't quite get my head around the inheritance structure. I'm normally fairly good at it, but this one just has too much overlap and I can't decide on it all.
I'm seeking to model sailing vessels - think the Age of Sail. Presumably therefore everything extends a Vessel class.
There are then several types of vessel style: rowed (galleys, canoes), square-rig, fore-and-aft rig, with different behaviour. Each of these is further subdivided into several other types. I can't decide whether this should be a series of interfaces or extensions of Vessel. Note also that there can be some cross over (a vessel can be both rowed and square rigged) which leads me to think interfaces?
Ships also have different behaviours: merchant vessels, men of war, privateer, pirates. I really can't work out whether this should be an interface or an extension of another class. There is no crossover of type in this case, however.
Finally there are several behaviours which individual ships can have. Merchants may be in a convoy (defend themselves) or independent (run away). Men of war almost always attack unless heavily outgunned... but may work in fleets, squadrons or independently. Privateers and pirates only attack if weaker - usually independently but occasionally in pairs. I'm assuming that this should be an interface too?
My big problem is that each style of ship (frigate, battleship etc) can fulfil almost any of these roles, so I can't build a simple solid inheritance structure. Frigate can't extend man-o-war because some are privateers. Sloop can't extend square rigged because some are fore and aft rigged. etcetc.
Any thoughts would be appreciated, I'm at a bit of a loose end.
Thanks
Make the "behavior" part as interfaces. That will help you assigning different behaviors to different ships without problem. Strategy Pattern is helpful here. In a nutshell, it states that the changeable and the constant properties should be separated.
For different means of movements, composition sounds like the most suitable answer at this moment.
Regarding the "but may work in fleets, squadrons or independently. Privateers and pirates only attack if weaker - usually independently but occasionally in pairs." part, I guess this has nothing to do with the inheritance tree. You can make "groups" of classes depending up on your need.
This might help you:
"There are then several types of vessel style:..." is specifying different possible behaviors. So "Movable" interface and its subclasses are for that. In the "Vessel" class, you can have a member of type "Movable". Since "Movable" is an interface, any class which implements it, is assignable to this member. So any subclass of Vessel can have any possible behavior, which we cna change at runtime as well. You can also make it an ArrayList. (Not sure if you actually want to do it or not). But if you need multiple different behaviors for a same vessel, you can do it.
When you say "Ships also have different behaviours:..." it feels like separate classes extending Vessel will satisfy this requirement. The sentence "There is no crossover of type in this case, however." makes life easier.
For the nest para "Finally there are several behaviours which individual ships can have...", you should add one more member for different possible behaviors. It will mostly be an ArrayList as one vessel will have multiple attack modes.
Fro the last para, if you can give some more details, I may be able to give some more ideas.
Ok, here are some ideas:
Vessels have one or more means of propulsion (oars, sails, etc.), which you can model by composition (e.g. have a list of propulsion methods).
Vessels use one of a variety of strategies (use the strategy pattern -- see http://en.wikipedia.org/wiki/Strategy_pattern -- for this)
Strategies which depend on the presence of other nearby ships will need some way of querying for those other ships -- so you'll need some sort of data structure that allows you to find which objects are near which other objects (look into the sort of data structures that are used for broad-phase collision detection)
As an alternative to the strategy pattern, you could switch to using a component-based design. In this setup, a vessel would be composed of one or more propulsion components, a strategy component, etc. You could then combine individual components as you see fit to make different vessels.
As an extra bonus, component-based designs are very helpful if you want your game to be data-driven, because you can just write a saver/loader for each different type of component, rather than for each possible type of vessel.
You might want to see here if you're interested in this sort of approach:
http://cowboyprogramming.com/2007/01/05/evolve-your-heirachy/
I want to provide a bit of advice based on the second paragraph of Bhusan's answer, which I quote here in full:
"Regarding the "but may work in fleets, squadrons or independently. Privateers and pirates only attack if weaker - usually independently but occasionally in pairs." part, I guess this has nothing to do with the inheritance tree. You can make "groups" of classes depending up on your need."
This leads me to believe that you additionally may want to consider the Composite pattern for certain groups of ships, at least those that are comprised of ships that all share the same behavior. See http://en.wikipedia.org/wiki/Composite_pattern where it is written that "the composite pattern describes that a group of objects are to be treated in the same way as a single instance of an object."
For instance you say "Merchants may be in a convoy (defend themselves)", but presumably they can defend themselves individually as well? This is all easier said than done of course, and my advice to you is to not over-think it and start with a very small subset of what you want to do as a protoype
You should separate the types and use the strategy pattern.
Immutable properties should be bound to the inheritance tree (e.g. a frigate won't turn into canoe, these are exact, non-behavioral types, inheriting from vessel) and everything that may change should be stored as references to behavioral types which are intrachangable. (Man-o-war is a behavioral type)
AI should be handled separately, for instance with states, but that is also have to be in a different module in your architecture.
Instead of thinking about it as strictly inheritance, I think you need to think about object Composition and how that can help make things easier.
For example: a Ship has a Behaviour. (Composition... the ship delegates to the behaviour to determine how to react to X situation)
A Pirate is a Behaviour (Inheritance from a Behaviour interface)...
You should not extend the Vessel class. Rather, a Vessel object should contain other objects that describe it. (This is known as Dependency Injection, to be annoyingly pedantic--forget I said that.) You have a Propulsion class, with instances for square-sails, fore-and-aft, and oars. You might want special instances of each for big and small hulls. You have a Behavior class to handle their attitude. Sometimes a simple integer works as well as a class. Your Armament class could be, instead, just a number of guns. (Or two numbers, one for poundage.) If you expect to ram, or have a ship loaded with rockets, or need to distinguish between long guns and carronades, you might need to go back to using the a class.
This lets you switch characteristics on the fly if you want--though you probably don't. Still, you can go from sail to using sweeps, or switch bold ship-of-the-line behavior with save-the-cargo behavior of a merchant to implement a captain losing his nerve. Anyway, it's there if you need it.

Check for intersection between many missles and enemy?

I want to create a class lets say called enemy 1, enemy 2, and enemy 3.
Enemy 1: Very easy to kill, but many.
Enemy 2: Harder to kill, but less of them.
Enemy 3: Boss, super hard to kill, only one.
Lets say that many is going to be 1,000. Less of them will be 100. Boss is of course one.
So it would be stupid to make 1,101 different instances for a game of just enemy. It would require to much code.
Now my fighter, which is sick, can fire a lot of missiles. Lets say 2,000 a minute for the sake of fun.
I need to check for collisions between the enemy and all the missiles. I plan only using 4 different instances. Which would be enemy1, enemy2, enemy3, and a missile.
Any ideas on how to go about this? Obviously I would need threads, but I am not sure how to check for collisions in this instance.
If you've got 1101 enemies wandering around the place then each of them will have their location, their damage, their ammo stock and so on, so you will need 1101 instances. You only need four classes. Then you create a whole array of instances of each class.
You also need an instance for every missile.
Collisions? Well, are you planning on using some 3d graphics gaming library for this? It'll probably handle collision detection. Or are your enemies all spheres? You need geometry...
So it would be stupid to make 1,101 different instances for a game of just enemy. It would require to much code.
Not at all. You may be confusing class with instance because you will in fact have to create 1,101 instances of these objects, but will only need code for 3 Enemy classes (or 1 class perhaps if you can make how hard it is to kill a property of the class). Likely you will have a collection, such as an ArrayList of Enemy.
The other answer handles collisions, but likely you will do this part in your model, not in your view code.

OO vs Simplicity when it comes to user interaction

As a project over summer while I have some downtime from Uni I am going to build a monopoly game. This question is more about the general idea of the problem however, rather than the specific task I'm trying to carry out.
I decided to build this with a bottom up approach, creating just movement around a forty space board and then moving on to interaction with spaces. I realised that I was quite unsure of the best way of proceeding with this and I am torn between two design ideas:
Giving every space its own object, all sub-classes of a Space object so the interaction can be defined by the space object itself. I could do this by implementing different land() methods for each type of space.
Only giving the Properties and Utilities (as each property has unique features) objects and creating methods for dealing with the buying/renting etc in the main class of the program (or Board as I'm calling it). Spaces like go and super tax could be implemented by a small set of conditionals checking to see if player is on a special space.
Option 1 is obviously the OO (and I feel the correct) way of doing things but I'd like to only have to handle user interaction from the programs main class. In other words, I don't want the space objects to be interacting with the player.
Why? Errr. A lot of the coding I've done thus far has had this simplicity but I'm not sure if this is a pipe dream or not for larger projects. Should I really be handling user interaction in an entirely separate class?
As you can see I am quite confused about this situation. Is there some way round this? And, does anyone have any advice on practical OO design that could help in general?
EDIT: Just like to note that I feel I lost a little focus on this question. I am interested in the general methodology of combining OO and any external action(command line, networking, GUI, file management etc) really.
In the end, it is up to you. That is the beauty of OO, in that it is subject to interpretation. There are some patterns that should usually be adhered to, but in general it is your decision how to approach it.
However, you should carefully consider what each actor in the system should know about the rest of it. Should a property really know about the player, his account balance, and the other players? Probably not. A property should know what it costs, how much its rent is, etc.
On the other hand, should the main playing thread be concerned about trivial matters such as paying rent? Probably not. Its main concern should be the state of the game itself, such as dice rolling, whether each player wants to trade or buy or unmortgage/mortgage, things like that.
Think for a moment about the action of landing on a square. Once landed, the player has 3 options:
Buy the property
Ignore the property
Pay rent
Now, which actor in the system knows all the information required to complete that. We have the Game class, which isn't concerned with such tedium. We have the Property, which doesn't really care about the players. But the Player object knows all this information. It keeps a record of what each player owns, and can easily access the proper data.
So, if it were me, I would make a Player.performMove(Die d) method. It has easy access to the accounts. This also allows for the least coupling among classes.
But in the end, it's up to you. I'm sure people have created Monopoly clones in perfect OO, as well as Functional or Procedural languages too. In the end, use what you know and keep refactoring until you're happy with the end design.
I agree option #1 seems better.
As for "user interaction" - it all depends. You could leave some of your code in another class. For example,
// in main class
user.landOn(space);
if (space.containsProperties()) doSomething(); // Option #1 for some user-interaction code
// in User.java
public void landOn(Space s) {
// do some checks
s.land(this);
if (s.containsProperties()) {...} // Option #2
// something else?
}
// in GetMoneySpace.java
#Override
public void land(User u) {
u.awardCash(200);
// Option #3 - no properties so nothing here
}
This is far more OOP-y (and better, in my opinion) than something like
if (space.isCashAwardSpace()) {
user.awardCash(space.getAward());
}
if (user.something()) doSomething(); // Some user-interaction code
I am not entirely sure if I understand it correctly. You have always such choice when designing software. I would personally go for the first choice. One argument is personal experience with small games (Scrabble), which prooved to me that good design matters for smaller projects as well. The point of OOP is that you can think differently about your design and you get some design benefits. For example imagine how hard it will be to add new field, change existing one, reuse behaviour of one field in multiple fields.
Your first approach is the one I'd go for. It encapsulates the behaviour where it's needed. So, you'd have Space subclasses for Utilities, Properties, GotoJail, FreeParking - basically all the different cateogires of spaces. What groups a category is it's common behaviour.
Your properties spaces may themselves have a group object as a member, e.g. to group all the dark blue properties together.
As to interaction with the user, you pass a Board (or better a GameController) instance to each space, so it knows which Game it is part of and can influence the game. The Space can then invoke specific actions on the board, such as, moving a piece, asking the user a question etc. The main point is that there is separation - the user interaction is not happening inside each Space - but the space is allowed to request that some interaction happens, or that a piece is moved. It's up to your GameController to actually do the interaction or move pieces etc. This separation makes it easy to test, and also provide alternative implementations as the need may arise (E.g. different game rules in different editions/countries?)
Go with the first design. You'd have a Property class, and subclass the special properties, overriding the default behavior.
As far as interaction, you could have a Token class, and move an instance of that around the board. You have to give the user some options, but yes, from the responses, you should be calling methods on objects, not putting complex logic in the user events.
Sample classes:
Property
name
price
baseRent
houseCount
hotelCount
mortgaged
getCurrentRent()
RailRoad extends Property
Utility extends Property
Board
properties
User
token
playerName
currentProperty
ownedProperties
buyProperty()
payRentOnProperty()
mortgageProperty()
move()
Option 2 doesn't make much sense, or at least it's not as clear to me as option 1. With option 1 you don't need to handle user interaction inside your space object. You could have in your main class or a separate class dedicated to handle user interaction:
public void move(Player p, int spaces){
Space landingSpace = board.getLandingSpace(p,spaces);
landingSpace.land(p); //apply your logic here
}
As you can see, the Space class is responsible for checking the Player p that intends to land on that space. It applies any custom logic, checks if it has enough money, if it's something that the player owns, etc. Each subclass of Space will have its own set of rules, as you described in option 1.
Part of the point of object-oriented design is to simplify the representation of the problem within the solution space (i.e., modeling the system in the computer). In this case, consider the relationships between objects. Is there enough functionality in a Space to warrant abstracting that into a class, or does it make more sense for there to be discrete Property and Utility classes unrelated to Space because of the unique features of both? Is a Property a special kind of Space, or merely a field within Space? These are the kinds of problems you probably will need to grapple with in designing the game.
As far as interaction, it's generally bad news for a design when you have a 'god class' that does all the work and merely asks the other classes for information. There are plenty of ways to fall into this trap; one way to determine whether you are dealing with a god class is to look for a class name including Manager or System. Thus, it's probably not the best idea to have some sort of "game manager" that asks all the other objects for data, makes all the changes, and keeps track of everything. Eliminate these as much as possible.
God classes violate the concept of encapsulation, which involves more than data hiding (though that's certainly a big part of it). Good encapsulation means that related methods and data are part of a single object. For example, a Property doesn't need to make requests of its owner, so a field containing a reference to the Player could violate encapsulation. Some of these encapsulation violations aren't obvious at all, and can be hard to spot. When designing the object, try to determine the smallest amount of information about the object that needs to be shared with external objects. Trim out anything unnecessary.
You can obviously go about this in a lot of ways, but my design would be something like this (iteration could certainly prove it wrong):
Space class that contains basic data and methods that are common to all spaces (such as their position on the board, occupied or not, etc.).
Subclasses moving from most common (Property and Utility) to most unique (Go, Jail, FreeParking, and so on; probably singletons) with fields and methods related to each.
Player class to contain player information.
GameState class that is concerned with game state; whose turn it is, how many houses are left in the bank, and so on.
Good luck with the game and your continued studies.
Naturally, Google is your friend, but here's a sampling of things I would recommend reading:
ATM simulation (this idea is
also discussed in Rebecca
Wirfs-Brock's book below)
Object-Oriented Design Heuristics - Arthur Riel
How Designs Differ (PDF), Designing Object-Oriented Software - Rebecca Wirfs-Brock

Categories