Example usage for java.lang Object wait

List of usage examples for java.lang Object wait

Introduction

In this page you can find the example usage for java.lang Object wait.

Prototype

public final native void wait(long timeoutMillis) throws InterruptedException;

Source Link

Document

Causes the current thread to wait until it is awakened, typically by being notified or interrupted, or until a certain amount of real time has elapsed.

Usage

From source file:org.apache.geode.internal.cache.OplogJUnitTest.java

/**
 * Tests reduction in size of disk stats when the oplog is rolled.
 *//*from  ww  w  . ja va2 s .com*/
@Category(FlakyTest.class) // GEODE-527: jvm sizing sensitive, non-thread-safe test hooks, time
                           // sensitive
@Test
public void testStatsSizeReductionOnRolling() throws Exception {
    final int MAX_OPLOG_SIZE = 500 * 2;
    diskProps.setMaxOplogSize(MAX_OPLOG_SIZE);
    diskProps.setPersistBackup(true);
    diskProps.setRolling(true);
    diskProps.setCompactionThreshold(100);
    diskProps.setSynchronous(true);
    diskProps.setOverflow(false);
    diskProps.setDiskDirsAndSizes(new File[] { dirs[0] }, new int[] { 4000 });
    final byte[] val = new byte[333];
    region = DiskRegionHelperFactory.getSyncPersistOnlyRegion(cache, diskProps, Scope.LOCAL);
    final DiskRegion dr = ((LocalRegion) region).getDiskRegion();
    final Object lock = new Object();
    final boolean[] exceptionOccured = new boolean[] { true };
    final boolean[] okToExit = new boolean[] { false };
    final boolean[] switchExpected = new boolean[] { false };

    // calculate sizes
    final int extra_byte_num_per_entry = InternalDataSerializer
            .calculateBytesForTSandDSID(getDSID((LocalRegion) region));
    final int key3_size = DiskOfflineCompactionJUnitTest.getSize4Create(extra_byte_num_per_entry, "key3", val);
    final int tombstone_key1 = DiskOfflineCompactionJUnitTest.getSize4TombstoneWithKey(extra_byte_num_per_entry,
            "key1");
    final int tombstone_key2 = DiskOfflineCompactionJUnitTest.getSize4TombstoneWithKey(extra_byte_num_per_entry,
            "key2");

    // TODO: move static methods from DiskOfflineCompactionJUnitTest to shared util class

    CacheObserver old = CacheObserverHolder.setInstance(new CacheObserverAdapter() {
        private long before = -1;
        private DirectoryHolder dh = null;
        private long oplogsSize = 0;

        @Override
        public void beforeSwitchingOplog() {
            cache.getLogger().info("beforeSwitchingOplog");
            if (!switchExpected[0]) {
                fail("unexpected oplog switch");
            }
            if (before == -1) {
                // only want to call this once; before the 1st oplog destroy
                this.dh = dr.getNextDir();
                this.before = this.dh.getDirStatsDiskSpaceUsage();
            }
        }

        @Override
        public void beforeDeletingCompactedOplog(Oplog oplog) {
            cache.getLogger().info("beforeDeletingCompactedOplog");
            oplogsSize += oplog.getOplogSize();
        }

        @Override
        public void afterHavingCompacted() {
            cache.getLogger().info("afterHavingCompacted");
            if (before > -1) {
                synchronized (lock) {
                    okToExit[0] = true;
                    long after = this.dh.getDirStatsDiskSpaceUsage();
                    // after compaction, in _2.crf, key3 is an create-entry,
                    // key1 and key2 are tombstones.
                    // _2.drf contained a rvvgc with drMap.size()==1
                    int expected_drf_size = Oplog.OPLOG_DISK_STORE_REC_SIZE + Oplog.OPLOG_MAGIC_SEQ_REC_SIZE
                            + Oplog.OPLOG_GEMFIRE_VERSION_REC_SIZE
                            + DiskOfflineCompactionJUnitTest.getRVVSize(1, new int[] { 0 }, true);
                    int expected_crf_size = Oplog.OPLOG_DISK_STORE_REC_SIZE + Oplog.OPLOG_MAGIC_SEQ_REC_SIZE
                            + Oplog.OPLOG_GEMFIRE_VERSION_REC_SIZE
                            + DiskOfflineCompactionJUnitTest.getRVVSize(1, new int[] { 1 }, false)
                            + Oplog.OPLOG_NEW_ENTRY_BASE_REC_SIZE + key3_size + tombstone_key1 + tombstone_key2;
                    int oplog_2_size = expected_drf_size + expected_crf_size;
                    if (after != oplog_2_size) {
                        cache.getLogger().info("test failed before=" + before + " after=" + after
                                + " oplogsSize=" + oplogsSize);
                        exceptionOccured[0] = true;
                    } else {
                        exceptionOccured[0] = false;
                    }
                    LocalRegion.ISSUE_CALLBACKS_TO_CACHE_OBSERVER = false;
                    lock.notify();
                }
            }
        }
    });
    try {

        LocalRegion.ISSUE_CALLBACKS_TO_CACHE_OBSERVER = true;
        cache.getLogger().info("putting key1");
        region.put("key1", val);
        // Disk space should have changed due to 1 put
        // assertTrue("stats did not increase after put 1 ", diskSpaceUsageStats() ==
        // calculatedDiskSpaceUsageStats());
        checkDiskStats();
        cache.getLogger().info("putting key2");
        region.put("key2", val);
        // assertTrue("stats did not increase after put 2", diskSpaceUsageStats() ==
        // calculatedDiskSpaceUsageStats());
        checkDiskStats();

        cache.getLogger().info("removing key1");
        region.remove("key1");
        cache.getLogger().info("removing key2");
        region.remove("key2");

        // This put will cause a switch as max-oplog size (900) will be exceeded (999)
        switchExpected[0] = true;
        cache.getLogger().info("putting key3");
        region.put("key3", val);
        cache.getLogger().info("waiting for compaction");
        synchronized (lock) {
            if (!okToExit[0]) {
                lock.wait(9000);
                assertTrue(okToExit[0]);
            }
            assertFalse(exceptionOccured[0]);
        }

        region.close();
    } finally {
        LocalRegion.ISSUE_CALLBACKS_TO_CACHE_OBSERVER = false;
        CacheObserverHolder.setInstance(old);
    }
}

From source file:com.codename1.impl.android.AndroidImplementation.java

/**
 * Calls the background fetch callback.  If the app is in teh background, this will
 * check to see if the lifecycle class implements the {@link com.codename1.background.BackgroundFetch}
 * interface.  If it does, it will execute its {@link com.codename1.background.BackgroundFetch#performBackgroundFetch(long, com.codename1.util.Callback) }
 * method.//from  www  .  j  av  a 2 s. c o m
 * @param blocking True if this should block until it is complete.
 */
public static void performBackgroundFetch(boolean blocking) {

    if (Display.getInstance().isMinimized()) {
        // By definition, background fetch should only occur if the app is minimized.
        // This keeps it consistent with the iOS implementation that doesn't have a 
        // choice
        final boolean[] complete = new boolean[1];
        final Object lock = new Object();
        final BackgroundFetch bgFetchListener = instance.getBackgroundFetchListener();
        final long timeout = System.currentTimeMillis() + 25000;
        if (bgFetchListener != null) {
            Display.getInstance().callSerially(new Runnable() {
                public void run() {
                    bgFetchListener.performBackgroundFetch(timeout, new Callback<Boolean>() {

                        @Override
                        public void onSucess(Boolean value) {
                            // On Android the OS doesn't care whether it worked or not
                            // So we'll just consume this.
                            synchronized (lock) {
                                complete[0] = true;
                                lock.notify();
                            }
                        }

                        @Override
                        public void onError(Object sender, Throwable err, int errorCode, String errorMessage) {
                            com.codename1.io.Log.e(err);
                            synchronized (lock) {
                                complete[0] = true;
                                lock.notify();
                            }
                        }

                    });
                }
            });

        }

        while (blocking && !complete[0]) {
            synchronized (lock) {
                try {
                    lock.wait(1000);
                } catch (Exception ex) {
                }
            }
            if (!complete[0]) {
                System.out.println(
                        "Waiting for background fetch to complete.  Make sure your background fetch handler calls onSuccess() or onError() in the callback when complete");

            }
            if (System.currentTimeMillis() > timeout) {
                System.out.println("Background fetch exceeded time alotted.  Not waiting for its completion");
                break;
            }

        }

    }
}

From source file:com.codename1.impl.android.AndroidImplementation.java

public PeerComponent createBrowserComponent(final Object parent) {
    if (getActivity() == null) {
        return null;
    }/*  w w  w  . j a  v a2 s .co m*/
    final AndroidImplementation.AndroidBrowserComponent[] bc = new AndroidImplementation.AndroidBrowserComponent[1];
    final Throwable[] error = new Throwable[1];
    final Object lock = new Object();

    getActivity().runOnUiThread(new Runnable() {
        @Override
        public void run() {

            synchronized (lock) {
                try {
                    WebView wv = new WebView(getActivity()) {

                        public boolean onKeyDown(int keyCode, KeyEvent event) {
                            switch (keyCode) {
                            case KeyEvent.KEYCODE_BACK:
                                Display.getInstance().keyPressed(AndroidImplementation.DROID_IMPL_KEY_BACK);
                                return true;
                            case KeyEvent.KEYCODE_MENU:
                                //if the native commands are used don't handle the keycode
                                if (Display.getInstance()
                                        .getCommandBehavior() != Display.COMMAND_BEHAVIOR_NATIVE) {
                                    Display.getInstance().keyPressed(AndroidImplementation.DROID_IMPL_KEY_MENU);
                                    return true;
                                }
                            }
                            return super.onKeyDown(keyCode, event);
                        }

                        public boolean onKeyUp(int keyCode, KeyEvent event) {
                            switch (keyCode) {
                            case KeyEvent.KEYCODE_BACK:
                                Display.getInstance().keyReleased(AndroidImplementation.DROID_IMPL_KEY_BACK);
                                return true;
                            case KeyEvent.KEYCODE_MENU:
                                //if the native commands are used don't handle the keycode
                                if (Display.getInstance()
                                        .getCommandBehavior() != Display.COMMAND_BEHAVIOR_NATIVE) {
                                    Display.getInstance().keyPressed(AndroidImplementation.DROID_IMPL_KEY_MENU);
                                    return true;
                                }
                            }
                            return super.onKeyUp(keyCode, event);
                        }
                    };
                    wv.setOnTouchListener(new View.OnTouchListener() {

                        @Override
                        public boolean onTouch(View v, MotionEvent event) {
                            switch (event.getAction()) {
                            case MotionEvent.ACTION_DOWN:
                            case MotionEvent.ACTION_UP:
                                if (!v.hasFocus()) {
                                    v.requestFocus();
                                }
                                break;
                            }
                            return false;
                        }
                    });
                    wv.getSettings().setDomStorageEnabled(true);
                    wv.requestFocus(View.FOCUS_DOWN);
                    wv.setFocusableInTouchMode(true);
                    bc[0] = new AndroidImplementation.AndroidBrowserComponent(wv, getActivity(), parent);
                    lock.notify();
                } catch (Throwable t) {
                    error[0] = t;
                    lock.notify();
                }
            }
        }
    });
    while (bc[0] == null && error[0] == null) {
        Display.getInstance().invokeAndBlock(new Runnable() {
            public void run() {
                synchronized (lock) {
                    if (bc[0] == null && error[0] == null) {
                        try {
                            lock.wait(20);
                        } catch (InterruptedException ex) {
                            ex.printStackTrace();
                        }
                    }
                }
            }

        });
    }
    if (error[0] != null) {
        throw new RuntimeException(error[0]);
    }
    return bc[0];
}