CDI extension dynamic update property

170 views Asked by At

I read some documents about CDI custom extensions and read some sample codes like Properties loader on this links : Link-A - Link-B.

I wrote a simple cdi extension like this codes .

public class SystemStatisticExtension implements Extension {

    public <T> void processInjectionTarget(@Observes ProcessInjectionTarget<T> pit) {
        AnnotatedType<T> at = pit.getAnnotatedType();
        InjectionTarget<T> it = pit.getInjectionTarget();
        if (at.isAnnotationPresent(Monitor.class)) {
            pit.setInjectionTarget(new MemoryInjectionPoint<>(it, at));
        }
    }
}

and this is my InjectionPointTarget implementation :

public class MemoryInjectionPoint<T> implements InjectionTarget<T> {

    private InjectionTarget<T> it;
    private AnnotatedType<T> at;
    private int kB = 1024;
    private int mB = kB / 1024;
    private int gB = mB / 1024;

    public MemoryInjectionPoint(InjectionTarget<T> it, AnnotatedType<T> at) {
        this.it = it;
        this.at = at;
    }

    @Override
    public void inject(T instance, CreationalContext<T> ctx) {
        it.inject(instance, ctx);
        int swapUsed = SystemPropertiesLoader.newInstance().getSwapUsed();
        Set<AnnotatedField<? super T>> annotatedFields = at.getFields();
        for (AnnotatedField<? super T> annotatedField : annotatedFields) {
            if (annotatedField.isAnnotationPresent(Memory.class)) {
                int memUsed = SystemPropertiesLoader.newInstance().getMemUsed();
                Memory memory = annotatedField.getAnnotation(Memory.class);
                Unit u = memory.unitType();
                switch (u) {
                    case KILOBYTE:
                        setFieldMemValue(instance, memUsed / kB, annotatedField);
                        break;
                    case MEGABYTE:
                        setFieldMemValue(instance, memUsed / mB, annotatedField);
                        break;
                    case GIGABYTE:
                        setFieldMemValue(instance, memUsed / gB, annotatedField);
                        break;
                }
            }
            if (at.isAnnotationPresent(Swap.class)) {
                Memory memory = annotatedField.getAnnotation(Memory.class);
                Unit u = memory.unitType();
                switch (u) {
                    case kILOBYTE:
                        setFieldSwapValue(instance, swapUsed / kB, annotatedField);
                        break;
                    case MEGABYTE:
                        setFieldSwapValue(instance, swapUsed / mB, annotatedField);
                        break;
                    case GIGABYTE:
                        setFieldSwapValue(instance, swapUsed / gB, annotatedField);
                        break;
                }
            }
        }
    }

    private void setFieldMemValue(T instance, int memUsed, AnnotatedField<? super T> annotatedField) {
        try {
            Field field = annotatedField.getJavaMember();
            field.setAccessible(true);
            field.setInt(instance, memUsed);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    private void setFieldSwapValue(T instance, int swapUsed, AnnotatedField<? super T> annotatedField) {
        try {
            Field field = annotatedField.getJavaMember();
            field.setAccessible(true);
            field.setInt(instance, swapUsed);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void postConstruct(T instance) {
        it.postConstruct(instance);
    }

    @Override
    public void preDestroy(T instance) {
        it.preDestroy(instance);
    }

    @Override
    public T produce(CreationalContext<T> ctx) {
        return it.produce(ctx);
    }

    @Override
    public void dispose(T instance) {
        it.dispose(instance);
    }

    @Override
    public Set<InjectionPoint> getInjectionPoints() {
        return it.getInjectionPoints();
    }
}

this is my SystemPropertiesLoader :

public class SystemPropertiesLoader {
    private static Supplier<Stream<String>> supplier;

    private SystemPropertiesLoader() {

    }

    public static SystemPropertiesLoader newInstance() {
        supplier = () -> {
            Stream<String> lines = Stream.empty();
            try {
                lines = Files.lines(Paths.get("/proc/meminfo"));
            } catch (IOException e) {
                e.printStackTrace();
            }
            return lines;
        };
        return new SystemPropertiesLoader();
    }

    public int getMemTotal() {
        return Integer.valueOf(
                supplier.get()
                        .findFirst()
                        .orElse("")
                        .split(":")[1]
                        .trim()
                        .replace(" kB", ""));
    }

    public int getMemFree() {
        return Integer.valueOf(
                supplier.get()
                        .skip(1)
                        .findFirst()
                        .orElse("")
                        .split(":")[1]
                        .trim()
                        .replace(" kB", ""));
    }

    public int getSwapTotal() {
        return Integer.valueOf(supplier.get()
                .skip(14)
                .findFirst()
                .orElse("")
                .split(":")[1]
                .trim()
                .replace(" kB", ""));
    }

    public int getSwapFree() {
        return Integer.valueOf(supplier.get()
                .skip(15)
                .findFirst()
                .orElse("")
                .split(":")[1]
                .trim()
                .replace(" kB", ""));
    }

    public int getMemUsed() {
        return getMemTotal() - getMemFree();
    }

    public int getSwapUsed() {
        return getSwapTotal() - getSwapFree();
    }
} 

and annotations :

@Target({FIELD, PARAMETER})
@Retention(RUNTIME)
public @interface Memory {
    Unit unitType() default Unit.MEGABYTE;
}

@Target({METHOD,TYPE})
@Retention(RUNTIME)
public @interface Monitor {
}

and this is my used case :

@Monitor
public class MemoryMonitor {

    @Memory
    private int memUsed;

    public int getMemUsed() {
        return memUsed;
    }
}

Now my problem is memUsed property not changed after update /proc/meminfo .
What is wrong ?
Can create dynamic CDI extension for do that ?
Note 1 : I copy and paste whole my code .
Note 2 : /proc/meminfo is information of memory used in Linux&Unix Operating systems supported proc filesystem .

1

There are 1 answers

0
Nikos Paraskevopoulos On

Expanding the comment, let me first say that injection occurs only once per instance of a bean. Beans are usually created once per scope so they are not automatically given the chance to adapt to changes that occur during their life. I can think of two things:

1) Use events to notify interested parties of changes

The principle is simple (the observer pattern). I do not know how to track the changes in /proc/meminfo (is java.nio.file.WatchService enough?), but as long as you have detected a change, the emit an event:

public class MemInfoEvent {
    private int memUsed;
    // constructor and getter
}

When you sense a change, call the following bean:

import javax.enterprise.event.Event;
...

@ApplicationScoped
public class MemInfoEventEmitter {
    @Inject
    private Event<MemInfo> memInfoEvent;

    public void handleMemInfoChange(int memUsed) {
        memInfoEvent.fire(new MemInfoEvent(memUsed));
    }
}

And watch the change, wherever needed:

public class BeanInterestedInMemChanges {
    public void memInfoChanged(@Observes MemInfoEvent e) {
        // do what you must
    }
}

2) Use a java.util.function.IntSupplier (or equivalent)

The supplier is a CDI bean that knows how to get the memUsed, e.g.:

@ApplicationScoped
public class MemUsedSupplier implements IntSupplier {
    private SystemPropertiesLoader systemPropertiesLoader = ...; // could be injected, if this is more appropriate

    @Override
    public int getAsInt() {
        return systemPropertiesLoader.getMemUsed();
    }
}

NOTE: The implementation above might be inefficient! Use as a starting point - proof of concept! The inefficiency is reading /proc/meminfo too many times, if getAsInt() is called frequently. You may want to implement some kind of caching/throttling.

You may even implement the MemoryMonitor in terms of the SystemPropertiesLoader, again taking care of potential inefficiencies.