0

Class A:

private String name;
private double[] data;
private double[] data1;
private double[] data2;
private double[] data3;
private double[] data4;

public A() (String name, double[] data, double[] data1... double[] data4) {
    this.name = name;
    this.data = data;
    ....
    this.data4= data4;
}

And getter methods...

Class B:

class B
String[] names = {"1", "2", "3", "4", "5", ... "20"};
Map<String, Report> types;

static {

    for(String name : names) {
        types.put(name, new A(name, getRandomData(), getRandomData(), getRandomData(), name.getData3(), name.getData4()))
    }
}

public static Collection<A> getDatas() {
    Collection<A> originals = types.values();
    List<A> result = new ArrayList<>();

    for (A original: originals) {
        A data = (new A(original.getData(),
                original.getDat1(),
                original.getData2().clone(),
                original.getData3().clone(),
                original.getData4().clone()));

        result.add(data);

    return result;
}

private static double[] getRandomData() {

    double[] result = new double[500000];
    Random random = new Random();

    for (int i = 0; i < result.length; i++) {
        result[i] = random.nextDouble();
    }

    return result;
}

I cannot change anything in Class B, but I can modify class A and also add extra classes.

I have implemented the flyweight pattern, but it generally prevents the memory usage from growing, not actually reducing the RAM usage.

I know the huge RAM usage is from getRandomData() method, which creates double[500000] random elements for each double[] array, but everything in class B needs to be retained.

If I delete clone(), it directly reduces the RAM usage from 800~MB to 400~MB, but I cannot change this one as well. I asked students who solved this problem, and they commonly got around with the .clone(), and someone told me to do the caching for flyweight pattern to cache .clone(), but there is no way to declone() a cloned array isn't it?.

So can someone please tell me how to cache the clone in FlyweightFactory class? I am spending hours solving this but I am still struggling with the question...

  • There's no "caching". Flyweight **shares** the data between the users, as soon as no users need it, it should be removed from the memory (while caching would keep it in memory). If you've implemented flyweight correctly, any "caching" would only increase memory usage. – Kayaman May 25 '20 at 06:23
  • That sounds like a (confusing) explanation of the flyweight pattern. If you implemented flyweight correctly, you're already "caching" it. Otherwise you didn't implement it correctly and you're not sharing the data properly. – Kayaman May 25 '20 at 07:20

0 Answers0