Example usage for java.lang OutOfMemoryError OutOfMemoryError

List of usage examples for java.lang OutOfMemoryError OutOfMemoryError

Introduction

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

Prototype

public OutOfMemoryError() 

Source Link

Document

Constructs an OutOfMemoryError with no detail message.

Usage

From source file:com.ginema.api.reflection.ReflectionUtilsTest.java

@Test
public void testShouldTestIsJDK() {
    assertTrue(ReflectionUtils.isJDKClass(1));
    assertTrue(ReflectionUtils.isJDKClass(new Date()));
    assertTrue(ReflectionUtils.isJDKClass(""));
    assertTrue(ReflectionUtils.isJDKClass(1L));
    assertTrue(ReflectionUtils.isJDKClass(new Long(1)));
    assertTrue(ReflectionUtils.isJDKClass(new OutOfMemoryError()));

}

From source file:com.streamsets.datacollector.execution.runner.common.TestProductionPipeline.java

@Test
public void testNoRerunOnJVMError() throws Exception {
    SourceOffsetTrackerCapture capture = new SourceOffsetTrackerCapture() {
        @Override/*from ww  w  .j ava2  s  .c  om*/
        public String produce(String lastSourceOffset, int maxBatchSize, BatchMaker batchMaker)
                throws StageException {
            throw new OutOfMemoryError();
        }
    };
    verifyRerunScenario(capture, PipelineStatus.RUN_ERROR);
}

From source file:edu.stanford.muse.email.MuseEmailFetcher.java

/** key method to fetch actual email messages. can take a long time.
 * @param session is used only to set the status provider object. callers who do not need to track status can leave it as null
 * @param selectedFolders is in the format <account name>^-^<folder name>
 * @param session is used only to put a status object in. can be null in which case status object is not set.
 * emailDocs, addressBook and blobstore/*from ww  w. ja va 2 s. c o m*/
 * @throws NoDefaultFolderException 
 * */
public void fetchAndIndexEmails(Archive archive, String[] selectedFolders, boolean useDefaultFolders,
        FetchConfig fetchConfig, HttpSession session) throws MessagingException, InterruptedException,
        IOException, JSONException, NoDefaultFolderException, CancelledException {
    setupFetchers(-1);

    long startTime = System.currentTimeMillis();
    if (session != null)
        session.setAttribute("statusProvider", new StaticStatusProvider("Starting to process messages..."));

    boolean op_cancelled = false, out_of_mem = false;

    BlobStore attachmentsStore = archive.getBlobStore();
    fetchConfig.downloadAttachments = fetchConfig.downloadAttachments && attachmentsStore != null;

    if (Util.nullOrEmpty(fetchers)) {
        log.warn("Trying to fetch email with no fetchers, setup not called ?");
        return;
    }

    setupFoldersForFetchers(fetchers, selectedFolders, useDefaultFolders);

    List<FolderInfo> fetchedFolderInfos = new ArrayList<FolderInfo>();

    // one fetcher will aggregate everything
    FetchStats stats = new FetchStats();
    MTEmailFetcher aggregatingFetcher = null;

    // a fetcher is one source, like an account or a top-level mbox dir. A fetcher could include multiple folders.
    long startTimeMillis = System.currentTimeMillis();
    for (MTEmailFetcher fetcher : fetchers) {
        // in theory, different iterations of this loop could be run in parallel ("archive" access will be synchronized)

        if (session != null)
            session.setAttribute("statusProvider", fetcher);

        fetcher.setArchive(archive);
        fetcher.setFetchConfig(fetchConfig);
        log.info("Memory status before fetching emails: " + Util.getMemoryStats());

        List<FolderInfo> foldersFetchedByThisFetcher = fetcher.run(); // this is the big call, can run for a long time. Note: running in the same thread, its not fetcher.start();

        // if fetcher was cancelled or out of mem, bail out of all fetchers
        // but don't abort immediately, only at the end, after addressbook has been built for at least the processed messages
        if (fetcher.isCancelled()) {
            log.info("NOTE: fetcher operation was cancelled");
            op_cancelled = true;
            break;
        }

        if (fetcher.mayHaveRunOutOfMemory()) {
            log.warn("Fetcher operation ran out of memory " + fetcher);
            out_of_mem = true;
            break;
        }

        fetchedFolderInfos.addAll(foldersFetchedByThisFetcher);

        if (aggregatingFetcher == null && !Util.nullOrEmpty(foldersFetchedByThisFetcher))
            aggregatingFetcher = fetcher; // first non-empty fetcher

        if (aggregatingFetcher != null)
            aggregatingFetcher.merge(fetcher);

        // add the indexed folders to the stats
        EmailStore store = fetcher.getStore();
        String fetcherDescription = store.displayName + ":" + store.emailAddress;
        for (FolderInfo fi : fetchedFolderInfos)
            stats.selectedFolders.add(new Pair<>(fetcherDescription, fi));
    }

    if (op_cancelled)
        throw new CancelledException();
    if (out_of_mem)
        throw new OutOfMemoryError();

    if (aggregatingFetcher != null) {
        stats.importStats = aggregatingFetcher.stats;
        if (aggregatingFetcher.mayHaveRunOutOfMemory())
            throw new OutOfMemoryError();
    }
    aggregatingFetcher = null; // save memory

    long endTimeMillis = System.currentTimeMillis();
    long elapsedMillis = endTimeMillis - startTimeMillis;
    log.info(elapsedMillis + " ms for fetch+index, Memory status: " + Util.getMemoryStats());

    List<EmailDocument> allEmailDocs = (List) archive.getAllDocs(); // note: this is all archive docs, not just the ones that may have been just imported

    archive.addFetchedFolderInfos(fetchedFolderInfos);

    if (allEmailDocs.size() == 0)
        log.warn("0 messages from email fetcher");

    EmailUtils.cleanDates(allEmailDocs);

    // create a new address book   
    if (session != null)
        session.setAttribute("statusProvider", new StaticStatusProvider("Building address book..."));
    AddressBook addressBook = EmailDocument.buildAddressBook(allEmailDocs, archive.ownerEmailAddrs,
            archive.ownerNames);
    log.info("Address book stats: " + addressBook.getStats());
    if (session != null)
        session.setAttribute("statusProvider", new StaticStatusProvider("Finishing up..."));
    archive.setAddressBook(addressBook);

    // we shouldn't really have dups now because the archive ensures that only unique docs are added
    // move sorting to archive.postprocess? 
    EmailUtils.removeDupsAndSort(allEmailDocs);

    // report stats
    stats.lastUpdate = new Date().getTime();

    stats.userKey = "USER KEY UNUSED"; // (String) JSPHelper.getSessionAttribute(session, "userKey");
    stats.fetchAndIndexTimeMillis = elapsedMillis;

    updateStats(archive, addressBook, stats);
    if (session != null)
        session.removeAttribute("statusProvider");
    log.info("Fetch+index complete: " + Util.commatize(System.currentTimeMillis() - startTime) + " ms");

}

From source file:de.hybris.platform.test.TransactionTest.java

@Test
public void testToException() {
    final ConsistencyCheckException businessExceptionSubClass = new ConsistencyCheckException("a", 0);
    final JaloBusinessException businessException = new JaloBusinessException("a", 0);
    final RuntimeException runtimeException = new RuntimeException();
    final Exception exception = new Exception();
    final Error error = new OutOfMemoryError();
    final Throwable throwable = new Throwable();

    //Business exception should be returned from the method
    {//w ww.  j  a  v a  2 s . c  om
        final JaloBusinessException result = Transaction.toException(businessException,
                JaloBusinessException.class);
        assertTrue(businessException == result);
    }

    //Subclass of business exception should be returned from the method (return type is the business exception)
    {
        final JaloBusinessException result = Transaction.toException(businessExceptionSubClass,
                JaloBusinessException.class);
        assertTrue(businessExceptionSubClass == result);
    }

    //This should not match and throw new RuntimeException
    {
        try {
            Transaction.toException(businessException, ConsistencyCheckException.class);
        } catch (final Throwable t) {
            assertEquals(RuntimeException.class, t.getClass());
            assertTrue(businessException == t.getCause());
        }
    }

    {
        try {
            Transaction.toException(runtimeException, JaloBusinessException.class);
        } catch (final Throwable t) {
            assertEquals(runtimeException, t);
        }
    }
    {
        try {
            Transaction.toException(exception, JaloBusinessException.class);
        } catch (final Throwable t) {
            assertEquals(RuntimeException.class, t.getClass());
            assertTrue(exception == t.getCause());
        }
    }
    {
        try {
            Transaction.toException(error, JaloBusinessException.class);
        } catch (final Throwable t) {
            assertEquals(error, t);
        }
    }
    {
        try {
            Transaction.toException(throwable, JaloBusinessException.class);
        } catch (final Throwable t) {
            assertEquals(RuntimeException.class, t.getClass());
            assertTrue(throwable == t.getCause());
        }
    }
}

From source file:com.mirth.connect.donkey.server.channel.Channel.java

private void handleDestinationChainThrowable(Throwable t) throws OutOfMemoryError, InterruptedException {
    Throwable cause;/*ww  w.j  a v  a  2  s  . co m*/
    if (t instanceof ExecutionException) {
        cause = t.getCause();
    } else {
        cause = t;
    }

    // TODO: make sure we are catching out of memory errors correctly here
    if (cause.getMessage() != null && cause.getMessage().contains("Java heap space")) {
        logger.error(cause.getMessage(), cause);
        throw new OutOfMemoryError();
    }

    if (cause instanceof CancellationException) {
        Thread.currentThread().interrupt();
        throw new InterruptedException();
    } else if (cause instanceof InterruptedException) {
        Thread.currentThread().interrupt();
        throw (InterruptedException) cause;
    }

    throw new RuntimeException(cause);
}

From source file:org.elasticsearch.ExceptionsHelperTests.java

public void testMaybeError() {
    final Error outOfMemoryError = new OutOfMemoryError();
    assertError(outOfMemoryError, outOfMemoryError);

    final DecoderException decoderException = new DecoderException(outOfMemoryError);
    assertError(decoderException, outOfMemoryError);

    final Exception e = new Exception();
    e.addSuppressed(decoderException);/*from w  ww .j a va2s.c  o  m*/
    assertError(e, outOfMemoryError);

    final int depth = randomIntBetween(1, 16);
    Throwable cause = new Exception();
    boolean fatal = false;
    Error error = null;
    for (int i = 0; i < depth; i++) {
        final int length = randomIntBetween(1, 4);
        for (int j = 0; j < length; j++) {
            if (!fatal && rarely()) {
                error = new Error();
                cause.addSuppressed(error);
                fatal = true;
            } else {
                cause.addSuppressed(new Exception());
            }
        }
        if (!fatal && rarely()) {
            cause = error = new Error(cause);
            fatal = true;
        } else {
            cause = new Exception(cause);
        }
    }
    if (fatal) {
        assertError(cause, error);
    } else {
        assertFalse(maybeError(cause, logger).isPresent());
    }

    assertFalse(maybeError(new Exception(new DecoderException()), logger).isPresent());

    Throwable chain = outOfMemoryError;
    for (int i = 0; i < MAX_ITERATIONS; i++) {
        chain = new Exception(chain);
    }
    assertFalse(maybeError(chain, logger).isPresent());
}

From source file:org.mule.transport.ftp.FtpMuleMessageFactoryStreamlessFailureTestCase.java

@Test
public void outOfMemoryError() throws Exception {
    assertThrowsException(new OutOfMemoryError());
}

From source file:org.sejda.impl.itext.component.split.PagesPdfSplitterTest.java

@Test(expected = OutOfMemoryError.class)
// issue #80//  ww w.j  a  v a  2s.c  o  m
public void testFinallyDoesntSwallowErrors() throws IOException, TaskException {
    InputStream inputStream = null;
    try {
        inputStream = getClass().getClassLoader().getResourceAsStream("pdf/test_no_outline.pdf");
        reader = new PdfReader(inputStream);
        PagesPdfSplitter<AbstractSplitByPageParameters> victim = spy(
                new PagesPdfSplitter<AbstractSplitByPageParameters>(reader, params));
        PdfCopier mockCopier = mock(PdfCopier.class);
        doReturn(mockCopier).when(victim).openCopier(any(PdfReader.class), any(File.class),
                any(PdfVersion.class));
        doThrow(new RuntimeException()).when(mockCopier).close();
        doThrow(new OutOfMemoryError()).when(mockCopier).addPage(reader, 1);
        NotifiableTaskMetadata taskMetadata = mock(NotifiableTaskMetadata.class);
        victim.split(taskMetadata);
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
}

From source file:org.springframework.aop.interceptor.ConcurrencyThrottleInterceptorTests.java

private void testMultipleThreads(int concurrencyLimit) {
    TestBean tb = new TestBean();
    ProxyFactory proxyFactory = new ProxyFactory();
    proxyFactory.setInterfaces(new Class[] { ITestBean.class });
    ConcurrencyThrottleInterceptor cti = new ConcurrencyThrottleInterceptor();
    cti.setConcurrencyLimit(concurrencyLimit);
    proxyFactory.addAdvice(cti);/*from w w  w . java 2  s.  com*/
    proxyFactory.setTarget(tb);
    ITestBean proxy = (ITestBean) proxyFactory.getProxy();

    Thread[] threads = new Thread[NR_OF_THREADS];
    for (int i = 0; i < NR_OF_THREADS; i++) {
        threads[i] = new ConcurrencyThread(proxy, null);
        threads[i].start();
    }
    for (int i = 0; i < NR_OF_THREADS / 10; i++) {
        try {
            Thread.sleep(5);
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
        threads[i] = new ConcurrencyThread(proxy,
                i % 2 == 0 ? (Throwable) new OutOfMemoryError() : (Throwable) new IllegalStateException());
        threads[i].start();
    }
    for (int i = 0; i < NR_OF_THREADS; i++) {
        try {
            threads[i].join();
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
    }
}