I have an immutable Point class and a CollectionPoint class which manages instances of my Point class. The CollectionPoint class owns points under its control and must synchronize concurrent activity. I have below what I think is a thread-safe solution but would like another opinion. Is this solution thread-safe?
class Main {
public static void main(String[] args) {
int N = 10;
double x = 0.0, y = 0.0;
for(int i=0;i<N;i++) {
x = (Math.random()*N);
y = (Math.random()*N);
Point p = new Point(x,y);
Thread cp = new CollectionPoint(p);
cp.start();
try {
cp.join();
} catch(InterruptedException e) {}
}
}
}
class CollectionPoint extends Thread{
// Class Needs to be thread safe
private List<Point> list = new ArrayList<>();
Point p;
public CollectionPoint(Point pi) {
p = pi;
}
public void run() {
synchronized(this) {
for(int i=0;i<1;i++) {
add(p);
}
}
display();
}
synchronized void add(Point x) {
list.add(x);
}
synchronized boolean search(Point p) {
for(int i=0;i<list.size();i++) {
if(list.contains(p)) {
return true;
}
}
return false;
}
synchronized double getAllX(int x) {
for(int i=0;i<list.size();i++) {
if(list.contains(p.x() == x)) {
return p.x();
}
}
return 0.0;
}
synchronized void replace(Point p, Point new_p) {
for(int i=0;i<list.size();i++) {
if(list.contains(p)) {
list.set(i, new_p);
}
}
}
synchronized void display() {
for(Point x : list) {
System.out.println("Point: "+x);
}
}
}
final class Point {
// Class Needs to be thread safe
private final double x,y;
public Point(double x0, double y0) {
x = x0;y = y0;
}
public double x() {return x;}
public double y() {return y;}
public String toString() {return "("+x+","+y+")";}
}