I've just released MObject. It's a tiny library to construct objects and object trees for mocking and stubbing in Python.
Go check it out!
Go check it out!
# gameoflife.py
"""
Simple Game of Life implementation for a fixed size board that
wraps at the edges. All cells, both alive and dead are part of
the representation.
"""
ALIVE = 1
DEAD = 0
class GameAnalyzer(object):
directions = ((-1,-1), (0,-1), (1,-1),
(-1, 0), (1, 0),
(-1, 1), (0, 1), (1, 1))
def __init__(self, board):
self.board = board
def cell_at(self, x, y):
y_wrapped = y % len(self.board)
x_wrapped = x % len(self.board[y_wrapped])
return self.board[y_wrapped][x_wrapped]
def neighbour_count(self, x, y):
return sum([self.cell_at(x + dx, y + dy) for dx, dy in self.directions])
def judge_cell(self, x, y):
rules = (DEAD, DEAD, self.cell_at(x, y), ALIVE, DEAD, DEAD, DEAD, DEAD, DEAD)
neighbour_count = self.neighbour_count(x, y)
return rules[neighbour_count]
def evolve(board):
a = GameAnalyzer(board)
return [[a.judge_cell(x, y) for x, _ in enumerate(row)] for y, row in enumerate(board)]
# gameoflife_test.py
from gameoflife import evolve, GameAnalyzer, ALIVE as x, DEAD as o
from nose.tools import assert_equal
def test_empty_board_remains_empty():
assert_equal(evolve([[o, o, o],
[o, o, o],
[o, o, o]]), [[o, o, o],
[o, o, o],
[o, o, o]])
def test_single_cell_dies():
assert_equal(evolve([[o, o, o],
[o, x, o],
[o, o, o]]), [[o, o, o],
[o, o, o],
[o, o, o]])
def test_stable_formation_remains():
assert_equal(evolve([[o, o, o],
[o, x, x],
[o, x, x]]), [[o, o, o],
[o, x, x],
[o, x, x]])
def test_blinker_blinks():
assert_equal(evolve([[o, o, o, o, o],
[o, o, o, o, o],
[o, x, x, x, o],
[o, o, o, o, o],
[o, o, o, o, o]]), [[o, o, o, o, o],
[o, o, x, o, o],
[o, o, x, o, o],
[o, o, x, o, o],
[o, o, o, o, o]])
assert_equal(evolve([[o, o, o, o, o],
[o, o, x, o, o],
[o, o, x, o, o],
[o, o, x, o, o],
[o, o, o, o, o]]), [[o, o, o, o, o],
[o, o, o, o, o],
[o, x, x, x, o],
[o, o, o, o, o],
[o, o, o, o, o]])
def test_board_wraps_around():
# South -> North
assert_equal(evolve([[o, o, o, o, o],
[o, o, o, o, o],
[o, o, o, o, o],
[o, o, o, o, o],
[o, x, x, x, o]]), [[o, o, x, o, o],
[o, o, o, o, o],
[o, o, o, o, o],
[o, o, x, o, o],
[o, o, x, o, o]])
# North -> South
assert_equal(evolve([[o, x, x, x, o],
[o, o, o, o, o],
[o, o, o, o, o],
[o, o, o, o, o],
[o, o, o, o, o]]), [[o, o, x, o, o],
[o, o, x, o, o],
[o, o, o, o, o],
[o, o, o, o, o],
[o, o, x, o, o]])
# East -> West
assert_equal(evolve([[o, o, o, o, o],
[o, o, o, o, x],
[o, o, o, o, x],
[o, o, o, o, x],
[o, o, o, o, o]]), [[o, o, o, o, o],
[o, o, o, o, o],
[x, o, o, x, x],
[o, o, o, o, o],
[o, o, o, o, o]])
# East -> West
assert_equal(evolve([[o, o, o, o, o],
[x, o, o, o, o],
[x, o, o, o, o],
[x, o, o, o, o],
[o, o, o, o, o]]), [[o, o, o, o, o],
[o, o, o, o, o],
[x, x, o, o, x],
[o, o, o, o, o],
[o, o, o, o, o]])
def check_neighbour_count(board, at, expected):
(x, y) = at
a = GameAnalyzer(board)
assert_equal(a.neighbour_count(x, y), expected)
def test_correct_neighbour_count_to_the_right():
check_neighbour_count([[o, o, o],
[o, o, x],
[o, o, o]], (1, 1), expected=1)
def test_correct_neighbour_count_to_the_right_and_right_down():
check_neighbour_count([[o, o, o],
[o, o, x],
[o, o, x]], (1, 1), expected=2)
def test_zero_neighbour_count_with_no_cells():
check_neighbour_count([[o, o, o],
[o, o, o],
[o, o, o]], (1, 1), expected=0)
def test_correct_neighbour_count_with_alive_cell_on_the_board_but_no_neighbours():
check_neighbour_count([[o, o, o],
[o, x, o],
[o, o, o]], (1, 1), expected=0)
def test_correct_neighbour_count_with_alive_cells_in_all_neighbour_positions():
check_neighbour_count([[x, x, x],
[x, x, x],
[x, x, x]], (1, 1), expected=8)
def test_correct_neighbour_count_for_corner_cell():
check_neighbour_count([[o, o, o],
[o, x, x],
[o, x, o]], (2, 2), expected=3)
Representing the whole board makes the tests easy to read (no additional comments needed, both the existing and expected board are all fleshed out), but input data may be on the large size.# gameoflife2.py
"""
Game of Life implementation for an expanding game. Live cells are
represented as x and y tuples stored in a set.
"""
class Game(object):
directions = ((-1,-1), (0,-1), (1,-1),
(-1, 0), (1, 0),
(-1, 1), (0, 1), (1, 1))
def __init__(self, live_cells):
self.live_cells = live_cells
def next_generation(self):
return set.union(self.survivors(), self.births())
def births(self):
return set([(x, y) for x, y in self.birth_candidates()
if len(self.live_neighbours(x, y)) == 3])
def birth_candidates(self):
return set.difference(self.all_neighbours(), self.live_cells)
def all_neighbours(self):
neighbours = [self.neighbours(x, y) for x, y in self.live_cells] or [set()]
return set.union(*neighbours)
def survivors(self):
return set([(x, y) for x, y in self.live_cells
if len(self.live_neighbours(x, y)) in (2, 3)])
def live_neighbours(self, x, y):
return set.intersection(self.live_cells, self.neighbours(x, y))
def neighbours(self, x, y):
return set([(x + dx, y + dy) for dx, dy in self.directions])
def game_generator(initial_state):
state = initial_state
while True:
state = Game(state).next_generation()
yield state
# gameoflife2_test.py
from gameoflife2 import game_generator, Game
def test_game_with_no_live_cells_remains_dead():
assert game_generator(set()).next() == set()
def test_a_single_live_cell_dies():
game = game_generator(set([(1, 1)]))
assert game.next() == set()
def test_stable_formation_remains():
"""
xxo xxo
xxo -> xxo
ooo ooo
"""
stable = set([(0, 0), (0, 1), (1, 0), (1, 1)])
game = game_generator(stable)
assert game.next() == stable
def test_blinker_blinks():
"""
ooo oxo ooo
xxx -> oxo -> xxx
ooo oxo ooo
"""
game = game_generator(set([(0, 1), (1, 1), (2, 1)]))
assert game.next() == set([(1, 0), (1, 1), (1, 2)])
assert game.next() == set([(0, 1), (1, 1), (2, 1)])
def test_game_plan_expands():
"""
oxo
xxx oxo
ooo -> oxo
ooo ooo
"""
game = game_generator(set([(0, 0), (1, 0), (2, 0)]))
assert game.next() == set([(1,-1), (1, 0), (1, 1)])
def test_Game_survivors_live_cell_with_two_and_three_neighbours_survive():
"""
xxo xxo
xxo -survivors-> oox
oxo oxo
"""
state = set([(0, 0), (0, 1), (1, 0), (1, 1), (1, 2)])
assert Game(state).survivors() == set([(0, 0), (1, 0), (1, 2)])
def test_Game_births_dead_cell_with_three_neighbours_come_alive():
"""
oxo ooo
oxo -births-> xox
oxo ooo
"""
state = set([(1, 0), (1, 1), (1, 2)])
assert Game(state).births() == set([(0, 1), (2, 1)])
def test_Game_birth_candidates_all_dead_cells_with_with_live_neighbour():
"""
ooo ooo
ooo -birth_candidates-> xxx
oxo xox
"""
state = set([(1, 2)])
assert Game(state).birth_candidates() == set([(0, 1), (1, 1), (2, 1), (0, 2),
(2, 2), (0, 3), (1, 3), (2, 3)])
def test_Game_live_neighbours_counts_correctly():
state = set([(0, 0), (0, 1), (1, 0)])
game = Game(state)
assert game.live_neighbours(0, 0) == set([(0, 1), (1, 0)])
assert game.live_neighbours(1, 1) == set([(0, 0), (0, 1), (1, 0)])
CREATE DATABASE sonar CHARACTER SET utf8 COLLATE utf8_general_ci;CREATE USER 'sonar' IDENTIFIED BY 'sonar';GRANT ALL ON sonar.* TO 'sonar'@'%' IDENTIFIED BY 'sonar';GRANT ALL ON sonar.* TO 'sonar'@'localhost' IDENTIFIED BY 'sonar';FLUSH PRIVILEGES;
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>datalogger</groupId>
<artifactId>DataLogger</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>DataLogger</name>
<url>http://maven.apache.org</url>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.7.2</version>
<configuration>
<test>**/*.java</test>
</configuration>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.5.10.201208310627</version>
<executions>
<execution>
<id>jacoco-initialize</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>aspectj-maven-plugin</artifactId>
<version>1.4</version>
<executions>
<execution>
<goals>
<goal>compile</goal>
<!-- use this goal to weave all your main classes -->
<goal>test-compile</goal>
<!-- use this goal to weave all your test classes -->
</goals>
</execution>
</executions>
<configuration>
<complianceLevel>1.6</complianceLevel>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>sonar-maven-plugin</artifactId>
<version>2.0</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>1.7</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<artifactSet>
<excludes>
<exclude>junit:junit</exclude>
<exclude>org.aspectj:aspectjrt</exclude>
<exclude>org.slf4j:slf4j-simple</exclude>
</excludes>
</artifactSet>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<properties>
<coverage.reports.dir>${basedir}/target/coverage-reports</coverage.reports.dir>
<sonar.core.codeCoveragePlugin>jacoco</sonar.core.codeCoveragePlugin>
<sonar.dynamicAnalysis>reuseReports</sonar.dynamicAnalysis>
</properties>
<dependencies>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.6.11</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>1.7.1</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.6.4</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.6.4</version>
</dependency>
</dependencies>
</project>
;; brainfuck.clj
(ns brainfuck
(:use clojure.test)
(:use midje.sweet))
; Dynamic meta data needed since 1.3 in order to override with dynamic binding.
; Only used for test really
(defn ^:dynamic read-input [] (.read *in*))
(defn str= [a b] (= (str a) (str b)))
(defn end? [elem] (nil? elem))
(defn loop? [elem] (sequential? elem))
(defn plus? [elem] (str= elem "+"))
(defn minus? [elem] (str= elem "-"))
(defn left? [elem] (str= elem "<"))
(defn right? [elem] (str= elem ">"))
(defn put? [elem] (str= elem "."))
(defn get? [elem] (str= elem ","))
(defn- exec-bf-internal [program the-memory the-mem-pos]
(loop [remain program
memory the-memory
mem-pos the-mem-pos]
(let [elem (first remain)]
(cond
(end? elem) {:mem memory :pos mem-pos}
(loop? elem) (if (> (nth memory mem-pos) 0)
; Enter loop body
(let [{:keys [mem pos]} (exec-bf-internal elem memory mem-pos)]
(recur remain mem pos))
; Skip loop body
(recur (rest remain) memory mem-pos))
(plus? elem) (recur (rest remain)
(assoc memory mem-pos (inc (nth memory mem-pos)))
mem-pos)
(minus? elem) (recur (rest remain)
(assoc memory mem-pos (dec (nth memory mem-pos)))
mem-pos)
(right? elem) (recur (rest remain)
memory
(inc mem-pos))
(left? elem) (recur (rest remain)
memory
(dec mem-pos))
(get? elem) (recur (rest remain)
(assoc memory mem-pos (int (read-input)))
mem-pos)
(put? elem) (do
(print (char (nth memory mem-pos)))
(recur (rest remain)
memory
mem-pos))
; Not a symbol which we recognize, just ignore it to allow comments, etc.
:default (recur (rest remain)
memory
mem-pos)))))
(defn- escape-conflicts [string]
(clojure.string/replace string "," "\",\""))
(defn- parse-bf [program]
; Make use of the Clojure like syntax and create a vector (nested if loops exist)
; containing the program by using the built in read-string
; This turned out to be quite hacky as Clojure considers "," as air so they had to
; be escaped before transforming the program into a Clojure vector
(read-string (escape-conflicts (clojure.string/join " " (seq (str "[" program "]"))))))
(defn exec-bf [program]
(exec-bf-internal (parse-bf program) (vec (replicate 10000 0)) 0)
1) ; Avoid returning the memory in the wrapping function
(ns brainfuck2
(:use clojure.test)
(:use midje.sweet))
; Dynamic meta data needed since 1.3 in order to override with dynamic binding.
; Only used for test really
(defn ^:dynamic read-input [& args] (.read *in*))
(def ^:dynamic *program*)
(def memory (atom nil))
(def mem-pos (atom nil))
(def prog-pos (atom nil))
(defn- fetch-instruction []
(nth *program* @prog-pos))
(defn- current-value []
(let [pos @mem-pos
val (nth @memory @mem-pos)]
val))
(defn- enter-loop? []
(not (zero? (current-value))))
(defn- exit-loop? []
(zero? (current-value)))
(defn- doto-mem [op]
(swap! memory assoc @mem-pos (op (current-value))))
(defn- doto-mem-pos [op]
(swap! mem-pos op))
(defn- doto-prog-pos [op]
(swap! prog-pos op))
(defn- put-char []
(print (char (current-value))))
(defn- get-char []
(doto-mem #(int (read-input %))))
; Used for searching block boundaries both forward and backwards
(defn- goto-block-bound [inc-fn dec-fn]
(loop [level 1]
(when (> level 0)
(do
(doto-prog-pos inc-fn)
(recur (condp = (fetch-instruction)
\[ (inc-fn level)
\] (dec-fn level)
level))))))
(defn- goto-block-start []
(goto-block-bound dec inc))
(defn- goto-block-end []
(goto-block-bound inc dec))
(defn- execute-instruction []
(case (fetch-instruction)
\[ (when (not (enter-loop?))
(goto-block-end))
\] (when (not (exit-loop?))
(goto-block-start))
\+ (doto-mem inc)
\- (doto-mem dec)
\> (doto-mem-pos inc)
\< (doto-mem-pos dec)
\. (put-char)
\, (get-char)
:default)) ; Ignore all other symbols to allow comments, etc.
(defn- exec-bf-internal []
(when (< @prog-pos (count *program*))
(do
(execute-instruction)
(doto-prog-pos inc)
(recur))))
(defn- reset-state []
(reset! memory (vec (replicate 10000 0)))
(reset! mem-pos 0)
(reset! prog-pos 0))
(defn exec-bf [program]
(reset-state)
(binding [*program* (seq program)] (exec-bf-internal)))
;; brainfuck5.clj
(ns brainfuck5
(:use clojure.test)
(:use midje.sweet))
(defn ^:dynamic read-input [] (.read *in*))
(def ^:dynamic *program*)
;(def state (atom nil))
(def prog-pos (atom nil))
(def memory (atom nil))
(def mem-pos (atom nil))
(defn- fetch-instruction []
(get *program* @prog-pos))
(defn- step-program-counter []
(swap! prog-pos inc))
(defn- current-value []
(nth @memory @mem-pos))
(defn- doto-mem [op]
(swap! memory assoc @mem-pos (op (current-value))))
(defn- doto-mem-pos [op]
(swap! mem-pos op))
(defn- put-char []
(print (char (current-value))))
(defn- get-char []
(doto-mem (fn [_] (int (read-input)))))
(def compile-block)
(def execute-block)
(defn- compile-loop []
(let [loop-block (compile-block)]
(fn []
(when (not (zero? (current-value)))
(do
(execute-block loop-block)
(recur))))))
(defn- compile-arithm [start]
(loop [steps start]
(case (fetch-instruction)
\+ (do
(step-program-counter)
(recur (inc steps)))
\- (do
(step-program-counter)
(recur (dec steps)))
(fn [] (doto-mem #(+ % steps))))))
(defn- compile-mem-step [start]
(loop [steps start]
(case (fetch-instruction)
\> (do
(step-program-counter)
(recur (inc steps)))
\< (do
(step-program-counter)
(recur (dec steps)))
(fn [] (doto-mem-pos #(+ % steps))))))
(defn- compile-put []
#(put-char))
(defn- compile-get []
#(get-char))
(defn- compile-block []
(loop [compiled []]
(if-let [inst (fetch-instruction)]
(do
(step-program-counter)
(case inst
\[ (recur (conj compiled (compile-loop)))
\] compiled
\+ (recur (conj compiled (compile-arithm 1)))
\- (recur (conj compiled (compile-arithm -1)))
\> (recur (conj compiled (compile-mem-step 1)))
\< (recur (conj compiled (compile-mem-step -1)))
\. (recur (conj compiled (compile-put)))
\, (recur (conj compiled (compile-get)))
(recur compiled))) ; Ignore all other symbols to allow comments, etc.
compiled)))
(defn- execute-block [block]
(doseq [instruction block]
(instruction)))
(defn- exec-bf-internal []
(let [prog (compile-block)]
(execute-block prog)
1))
(defn- reset-state []
(reset! prog-pos 0)
(reset! memory (vec (replicate 10000 0)))
(reset! mem-pos 0))
(defn exec-bf [program]
(reset-state)
(binding [*program* (into [] (seq program))] (exec-bf-internal)))
;; brainfuck5.clj
; Some tests
(def a-str (str "+++++++++++++++++++++++++++++++++"
"+++++++++++++++++++++++++++++++++"
"+++++++++++++++++++++++++++++++"))
(def hello-world (str "++++++++++[>+++++++>++++++++++>+++>+<<<<-]"
">++.>+.+++++++..+++.>++.<<+++some comments in the middle"
"++++++++++++."
">.+++.------.--------.>+.>."))
(defn dummy-read []
\a)
(fact (with-out-str (exec-bf (str a-str "."))) => "a")
(fact (with-out-str (exec-bf (str a-str "+-."))) => "a")
(fact (with-out-str (exec-bf (str a-str ">" a-str "++" ".<."))) => "ca")
(fact (with-out-str (exec-bf "+++++[[>+++++++++++++++++++<-]]>++.")) => "a")
(fact (with-out-str (exec-bf hello-world)) => "Hello World!\n")
(fact (binding [read-input dummy-read] (with-out-str (exec-bf ",+."))) => "b")
// PrimeMain.java
package primegenerator;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class PrimeMain {
public static void main(String[] args) {
ClassPathXmlApplicationContext beanFactory = new ClassPathXmlApplicationContext(
"PrimeGeneratorApplication.xml");
PrimeGenerator generator = (PrimeGenerator) beanFactory.getBean("generator");
generator.generatePrimes(2000000);
}
}
// FileDestination.java
package primegenerator;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
public class FileDestination implements IPrimeDestination {
private final String fileName;
public FileDestination(String fileName) {
this.fileName = fileName;
}
@Override
public void put(long prime) {
Writer out = null;
try {
out = new OutputStreamWriter(new FileOutputStream(fileName, true));
out.write(Long.toString(prime) + "\n");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
// IPrimeDestination.java
package primegenerator;
public interface IPrimeDestination {
public void put(long prime);
}
// PrimeGenerator.java
package primegenerator;
import org.springframework.beans.factory.annotation.Autowired;
public class PrimeGenerator {
@Autowired
private IPrimeDestination destination;
private boolean isPrime(long number) {
for(long i = 2; i<Math.sqrt(number); i++) {
if(number % i == 0) {
return false;
}
}
return true;
}
public void generatePrimes(long upTo) {
long startTime = System.currentTimeMillis();
for(long i = 3; i < upTo; i++) {
if(isPrime(i)) {
destination.put(i);
}
}
System.out.println("Done generating primes, time = " +
(System.currentTimeMillis() - startTime) + " ms");
}
}
// PrimeMain.java
package primegenerator;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class PrimeMain {
public static void main(String[] args) {
ClassPathXmlApplicationContext beanFactory = new ClassPathXmlApplicationContext(
"PrimeGeneratorApplication.xml");
PrimeGenerator generator = (PrimeGenerator) beanFactory.getBean("generator");
generator.generatePrimes(2000000);
}
}
// ..\PrimeGeneratorApplication.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="primegenerator" />
<bean id="generator" class="primegenerator.PrimeGenerator" />
<bean id="destination" class="primegenerator.FileDestination">
<constructor-arg value="primes.txt" />
</bean>
</beans>
Generating all primes under 200000 takes about 12500 milliseconds with above application. To profile the application run kit with an upper limit high enough to allow for some profiling. In the left window your java process will show up and you can choose to connect to it. Then, using the sampler, and selecting CPU will result in a screen like that below.// FileDestination.java
package primegenerator;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
public class FileDestination implements IPrimeDestination {
private final String fileName;
private Writer out;
public FileDestination(String fileName) {
this.fileName = fileName;
}
public void initBean() {
out = null;
try {
out = new OutputStreamWriter(new FileOutputStream(fileName, true));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
System.out.println("Init called");
}
public void destroyBean() {
try {
if(out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Destroy called");
}
@Override
public void put(long prime) {
try {
out.write(Long.toString(prime) + "\n");
} catch (IOException e) {
e.printStackTrace();
}
}
}
// PrimeMain.java
package primegenerator;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class PrimeMain {
public static void main(String[] args) {
ClassPathXmlApplicationContext beanFactory = new ClassPathXmlApplicationContext(
"PrimeGeneratorApplication.xml");
beanFactory.registerShutdownHook();
PrimeGenerator generator = (PrimeGenerator) beanFactory.getBean("generator");
generator.generatePrimes(200000);
}
}
// ..\PrimeGeneratorApplication.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd"
default-init-method="initBean"
default-destroy-method="destroyBean">
<context:component-scan base-package="primegenerator" />
<bean id="generator" class="primegenerator.PrimeGenerator" />
<bean id="destination" class="primegenerator.FileDestination">
<constructor-arg value="primes.txt" />
</bean>
</beans>
// PrimeGenerator.java
package primegenerator;
import org.springframework.beans.factory.annotation.Autowired;
public class PrimeGenerator {
@Autowired
private IPrimeDestination destination;
public void generatePrimes(int upTo) {
long startTime = System.currentTimeMillis();
int N = upTo;
// assume 2 and all odd integers >= 3 are prime
boolean[] isPrime = new boolean[N + 1];
isPrime[2] = true;
for (int i = 3; i <= N; i+=2) {
isPrime[i] = true;
}
// mark non-primes <= N using Sieve of Eratosthenes
for (int i = 2; i*i <= N; i++) {
// if i is prime, then mark multiples of i as nonprime
// suffices to consider multiples i, i+1, ..., N/i
if (isPrime[i]) {
for (int j = i; i*j <= N; j++) {
isPrime[i*j] = false;
}
}
}
// Output primes
for (int i = 2; i <= N; i++) {
if (isPrime[i]) destination.put(i);
}
System.out.println("Done generating primes, time = " +
(System.currentTimeMillis() - startTime) + " ms");
}
}