Package net.algart.finalizing

Examples of net.algart.finalizing.Finalizer


                + " " + DemoUtils.possibleArg(true) + " [gc [waitAfterGc]]");
            return;
        }
        System.out.println(Arrays.SystemSettings.globalMemoryModel());
        System.out.println();
        Finalizer fin = new Finalizer();
        fin.setPriority(Thread.MIN_PRIORITY);
        for (int m = 0; m < 7; m++) {
            UpdatableArray aSource = DemoUtils.createTestUnresizableArray(args[0],
                args[0].equals("boolean") ? 80 : 20);
            UpdatableArray aSourceClone = aSource.updatableClone(Arrays.SystemSettings.globalMemoryModel());
            final int identityHashCode = System.identityHashCode(aSource);
            System.out.println("Protection method #" + (m + 1) + ": "
                + (m == SYNTAX ? "SYNTACTICAL ONLY"
                : m == CLONE ? "UPDATABLE CLONE"
                : m == IMMUTABLE ? "IMMUTABLE VIEW"
                : m == TRUSTED ? "TRUSTED IMMUTABLE VIEW"
                : m == CNW ? "COPY-ON-NEXT-WRITE"
                : m == TRUSTED_CNW ? "TRUSTED IMMUTABLE + COPY-ON-NEXT-WRITE"
                : m == CNW_TRUSTED ?
                "COPY-ON-NEXT-WRITE + TRUSTED IMMUTABLE (should be equivalent to the previous method)"
                : "IMPOSSIBLE")
                + " (array @" + Integer.toHexString(identityHashCode) + ")");
            Array aR = m == 0 ? aSource
                : m == CLONE ? aSource.updatableClone(Arrays.SystemSettings.globalMemoryModel())
                : m == IMMUTABLE ? aSource.asImmutable()
                : m == TRUSTED ? aSource.asTrustedImmutable()
                : m == CNW ? aSource.asCopyOnNextWrite()
                : m == TRUSTED_CNW ? aSource.asTrustedImmutable().asCopyOnNextWrite()
                : m == CNW_TRUSTED ? aSource.asCopyOnNextWrite().asTrustedImmutable()
                : null;
            final Array dup = aR.shallowClone();
            // - must be here, not inside the following inner class, to allow deallocation of aR
            fin.invokeOnDeallocation(aR, new Runnable() {
                public void run() {
                    System.out.println("~~~ Checking array @"
                        + Integer.toHexString(identityHashCode) + " while finalization...");
                    long t = System.currentTimeMillis();
                    while (System.currentTimeMillis() - t < 750) ; //emulation of long calculations
                    try {
                        dup.checkUnallowedMutation();
                        System.out.println("~~~ Finalization OK");
                    } catch (UnallowedMutationError ex) {
                        System.out.println("~~~ UnallowedMutationError CAUGHT while finalization:");
                        System.out.println("    \"" + ex.getMessage() + "\"");
                    }
                }
            });
            DemoUtils.showArray("The original array:  ", aSource);
            DemoUtils.showArray("The protected array: ", aR);
            System.out.println("Attempt to get element #3");
            System.out.println("The element #3 is " + aR.getElement(3));

            if (aR instanceof UpdatableArray) {
                System.out.println("It is updatable!");
                System.out.println("Attempt to change element #3");
                DemoUtils.changeTestArray((UpdatableArray) aR, 3, 0);
                DemoUtils.showArray("The changed array:   ", aR);
            }

            if (aR instanceof DirectAccessible) {
                if (((DirectAccessible) aR).hasJavaArray()) {
                    System.out.println("It can be accessible as array");
                    System.out.println("Attempt to quickly read element #4");
                    Object array = ((DirectAccessible) aR).javaArray();
                    if (array instanceof boolean[])
                        System.out.println("The element #4 is " + ((boolean[]) array)[4]);
                    else if (array instanceof char[])
                        System.out.println("The element #4 is " + ((char[]) array)[4]);
                    else if (array instanceof byte[])
                        System.out.println("The element #4 is " + ((byte[]) array)[4]);
                    else if (array instanceof short[])
                        System.out.println("The element #4 is " + ((short[]) array)[4]);
                    else if (array instanceof int[])
                        System.out.println("The element #4 is " + ((int[]) array)[4]);
                    else if (array instanceof long[])
                        System.out.println("The element #4 is " + ((long[]) array)[4]);
                    else if (array instanceof float[])
                        System.out.println("The element #4 is " + ((float[]) array)[4]);
                    else if (array instanceof double[])
                        System.out.println("The element #4 is " + ((double[]) array)[4]);
                    else
                        System.out.println("The element #4 is " + ((Object[]) array)[4]);
                    aR.checkUnallowedMutation();
                    System.out.println("Attempt to quickly write element #4");
                    if (array instanceof boolean[])
                        ((boolean[]) array)[4] = false;
                    else if (array instanceof char[])
                        ((char[]) array)[4] = 0;
                    else if (array instanceof byte[])
                        ((byte[]) array)[4] = (byte) 0;
                    else if (array instanceof short[])
                        ((short[]) array)[4] = (short) 0;
                    else if (array instanceof int[])
                        ((int[]) array)[4] = 0;
                    else if (array instanceof long[])
                        ((long[]) array)[4] = 0;
                    else if (array instanceof float[])
                        ((float[]) array)[4] = 0;
                    else if (array instanceof double[])
                        ((double[]) array)[4] = 0;
                    else
                        ((Object[]) array)[4] = null;
                    DemoUtils.showArray("The changed array: ", aR);
                    try {
                        aR.checkUnallowedMutation();
                        if (m == TRUSTED || m == TRUSTED_CNW || m == CNW_TRUSTED)
                            throw new RuntimeException("Internal error: unallowed array change was not detected!");
                    } catch (UnallowedMutationError ex) {
                        System.out.println("UnallowedMutationError CAUGHT:");
                        System.out.println("    \"" + ex.getMessage() + "\"");
                    }
                    try {
                        dup.checkUnallowedMutation();
                        if (m == TRUSTED)
                            throw new RuntimeException("Internal error: unallowed array change was not detected "
                                + "in a duplicate!");
                        // changes in copy-on-write arrays cannot be caught here:
                        // duplicate will cease to be a view after array() call
                    } catch (UnallowedMutationError ex) {
                        System.out.println("UnallowedMutationError CAUGHT in a duplicate:");
                        System.out.println("    \"" + ex.getMessage() + "\"");
                    }
                } else {
                    System.out.println("It implements DirectAccessible, but cannot be accessible as array");
                }
            } else {
                System.out.println("It doesn't implement DirectAccessible");
            }
            if (!aSource.equals(aSourceClone)) {
                System.out.println("UNFORTUNATELY, the original array was changed");
                DemoUtils.showArray("The original array: ", aSource);
                if (m == CLONE || m == IMMUTABLE || m == CNW || m == TRUSTED_CNW || m == CNW_TRUSTED)
                    throw new RuntimeException("Internal error: array should not be changed here!");
            } else {
                System.out.println("The original array IS NOT MODIFIED!");
                if (m == SYNTAX || (m == TRUSTED && SimpleMemoryModel.isSimpleArray(aSource)
                    && !(aSource instanceof BitArray)))
                    throw new RuntimeException("Internal error: array should be changed here!");
            }
            System.out.println();
            System.out.println();
        }
        System.out.println("Number of finalization tasks: " + fin.activeTasksCount());
        if (args.length >= 2 && args[1].equalsIgnoreCase("gc")) {
            System.out.println("Calling System.gc()");
            System.gc();
//            fin.shutdownNow(); // uncomment this to cancel finalization
            if (args.length >= 3 && args[2].equalsIgnoreCase("waitaftergc")) {
                System.out.println("Waiting for all finalization tasks...");
                while (true) {
                    int count = fin.activeTasksCount();
                    System.out.println("Number of finalization tasks: " + count);
                    if (count == 0)
                        break;
                    try {
                        Thread.sleep(300);
View Full Code Here


    public void test(final File file, long length) throws IOException, InterruptedException {
        if (file.exists()) {
            System.out.println("This file already exists: please choose another file name.");
            return;
        }
        Finalizer fin = new Finalizer();
        RandomAccessFile raf = new RandomAccessFile(file, "rw");
        raf.setLength(length);
        pause("File " + file + " is created: " + raf.length() + " bytes");

        byte[] arr1 = new byte[maxStringLength / 2], arr2 = new byte[maxStringLength / 2];
        raf.seek(0); raf.read(arr1);
        raf.seek(raf.length()-arr2.length); raf.read(arr2);
        pause("Bytes at start and end of file: " + toString(ByteBuffer.wrap(arr1))
            + "; " + toString(ByteBuffer.wrap(arr2)));

        MappedBuffers mb = new MappedBuffers();
        FileChannel fc = raf.getChannel();
        mb.bb1 = fc.map(FileChannel.MapMode.READ_WRITE, 0, length);
        pause("File channel is created and mapped: " + mb.bb1.limit() + " bytes " + toString(mb.bb1));

        fillByteBuffer(mb.bb1, 0, Math.min(1000000, mb.bb1.limit()), (byte)1);
        pause("First 1000000 bytes are filled by 1: " + toString(mb.bb1));

        mb.bb2 = fc.map(FileChannel.MapMode.READ_WRITE, 500, length - 500);
        pause("Another map is created: " + mb.bb2.limit() + " bytes " + toString(mb.bb2));

        mb.bb1.force();
        pause("Data are flushed to disk: please view the file right now from a parallel task",
            "the file size will be increased by 2000000");

        try {
            raf.setLength(length + 2000000);
            pause("File " + file + " is resized: " + raf.length() + " bytes");
        } catch (IOException ex) {
            ex.printStackTrace();
            pause("New file length: " + raf.length() + " bytes");
        }
        mb.bb3 = fc.map(FileChannel.MapMode.READ_WRITE, 0, raf.length());
        pause("File is mapped again: " + mb.bb3.limit() + " bytes " + toString(mb.bb3),
            "the file size will be set to 800 bytes");

        if (gcBeforeReducing) {
            mb = new MappedBuffers();
            System.gc();
            pause("[System.gc() called]");
        }
        try {
            raf.setLength(800);
            pause("File " + file + " is resized to 800: " + raf.length() + " bytes");
        } catch (IOException ex) {
            ex.printStackTrace();
            pause("New file length: " + raf.length() + " bytes");
        }
        mb.bb4 = fc.map(FileChannel.MapMode.READ_WRITE, 0, raf.length());
        pause("File is mapped again: " + mb.bb4.limit() + " bytes " + toString(mb.bb4));

        if (reduceByFinalizer) {
            // This call disables file removing on exit!
            fin.invokeOnDeallocation(mb, new Runnable() {
                public void run() {
                    try {
                        RandomAccessFile rafTemp = new RandomAccessFile(file, "rw");
                        rafTemp.setLength(700);
                        System.out.println("-- File " + file + " is resized to 700: " + rafTemp.length() + " bytes");
                    } catch (IOException ex) {
                        ex.printStackTrace();
                        System.out.println("-- New file length: " + file.length() + " bytes");
                    }
                }
            });
            pause("setLength(700) is planned on storage deallocation",
                "the file will be closed");
        }
        raf.close();
        pause("File is closed; previous mapping: " + mb.bb4.limit() + " bytes " + toString(mb.bb4),
            "the file will be deleted");

        if (gcBeforeDeleting) {
            mb = new MappedBuffers();
            System.gc();
            pause("[System.gc() called]");
        }
        boolean deleteResult = file.delete();
        pause("File is " + (deleteResult ? "" : "NOT ") + "deleted");

        if (deleteResult && file.exists())
            throw new AssertionError("File was not deleted!");

        if (!deleteResult && deleteInFinalize) {
            mb.fileToDeleteInFinalize = file;
            mb.new FinHolder();
            pause("File will be deleted in finalize()");
        }

        if (!deleteResult && deleteByFinalizer) {
            fin.invokeOnDeallocation(mb, new Runnable() {
                public void run() {
                    boolean deleteResult = file.delete();
                    System.out.println("-- File is " + (deleteResult ? "" : "NOT ") + "deleted");
                }
            });
            pause("File deletion is planned on storage deallocation");
        }

        mb = new MappedBuffers();
        if (gcBeforeTestFinish) {
            System.gc();
            pause("[System.gc() called]");
        }
        if (!deleteResult) {
            if (ownShutdownCleaner) {
                TempFiles.deleteOnExit(file);
                pause("File will be deleted on exit by " + TempFiles.class, "the test will be finished");
            } else {
                file.deleteOnExit();
                pause("File will be deleted on exit", "the test will be finished");
            }
        }
        if (gcBeforeExit) {
            long t = System.currentTimeMillis();
            System.out.println("Active task count: " + fin.activeTasksCount());
            while (fin.activeTasksCount() > 0) {
                System.runFinalization();
                System.gc();
                Thread.sleep(50);
                if (System.currentTimeMillis() - t > 5000)
                    break;
                System.out.println("Active task count: " + fin.activeTasksCount());
            }
            for (int k = 0; k < 5; k++) {
                // finalizing some additional objects that could be
                // referred from finalization tasks performed above
                System.runFinalization();
View Full Code Here

TOP

Related Classes of net.algart.finalizing.Finalizer

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.