01: /*
02: * This file is part of JGAP.
03: *
04: * JGAP offers a dual license model containing the LGPL as well as the MPL.
05: *
06: * For licensing information please see the file license.txt included with JGAP
07: * or have a look at the top of class org.jgap.Chromosome which representatively
08: * includes the JGAP license policy applicable for any file delivered with JGAP.
09: */
10: package org.jgap.impl;
11:
12: import org.jgap.*;
13:
14: /**
15: * Provides a pooling mechanism for Chromosome instances so that
16: * discarded Chromosome instances can be recycled, thus saving memory and the
17: * overhead of constructing new ones from scratch each time.
18: *
19: * @author Neil Rotstan
20: * @author Klaus Meffert
21: * @since 1.0
22: */
23: public class ChromosomePool implements IChromosomePool {
24: /** String containing the CVS revision. Read out via reflection!*/
25: private static final String CVS_REVISION = "$Revision: 1.12 $";
26:
27: /**
28: * The internal pool in which the Chromosomes are stored.
29: */
30: private Pool m_chromosomePool;
31:
32: /**
33: * Constructor.
34: *
35: * @author Neil Rostan
36: * @since 1.0
37: */
38: public ChromosomePool() {
39: m_chromosomePool = new Pool();
40: }
41:
42: /**
43: * Attempts to acquire an Chromosome instance from the chromosome pool.
44: * It should be noted that nothing is guaranteed about the value of the
45: * Chromosome's genes and they should be treated as undefined.
46: *
47: * @return a Chromosome instance from the pool or null if no Chromosome
48: * instances are available in the pool
49: *
50: * @author Neil Rostan
51: * @since 1.0
52: */
53: public synchronized IChromosome acquireChromosome() {
54: return (IChromosome) m_chromosomePool.acquirePooledObject();
55: }
56:
57: /**
58: * Releases a Chromosome to the pool. It's not required that the Chromosome
59: * originated from the pool--any Chromosome can be released to it. This
60: * method will invoke the cleanup() method on each of the Chromosome's
61: * genes prior to adding it back to the pool.
62: *
63: * @param a_chromosome the Chromosome instance to be released into the pool
64: *
65: * @author Neil Rostan
66: * @since 1.0
67: */
68: public synchronized void releaseChromosome(
69: final IChromosome a_chromosome) {
70: if (a_chromosome == null) {
71: throw new IllegalArgumentException(
72: "Chromosome instance must not be null!");
73: }
74: // First cleanup the chromosome's genes before returning it back
75: // to the pool.
76: // -------------------------------------------------------------
77: Gene[] genes = a_chromosome.getGenes();
78: int size = a_chromosome.size();
79: for (int i = 0; i < size; i++) {
80: genes[i].cleanup();
81: }
82: // Now add it to the pool.
83: // -----------------------
84: m_chromosomePool.releaseObject(a_chromosome);
85: }
86: }
|