Search in sources :

Example 16 with ThreadInterruptedError

use of org.eclipse.scout.rt.platform.util.concurrent.ThreadInterruptedError in project scout.rt by eclipse.

the class TimeoutRunContextStatement method evaluate.

@Override
public void evaluate() throws Throwable {
    final SafeStatementInvoker invoker = new SafeStatementInvoker(m_next);
    final IFuture<Void> future = Jobs.schedule(invoker, Jobs.newInput().withRunContext(// Run in new TX, because the same TX is not allowed to be used by multiple threads.
    RunContext.CURRENT.get().copy().withTransactionScope(TransactionScope.REQUIRES_NEW)).withName("Running test with support for JUnit timeout"));
    try {
        future.awaitDone(m_timeoutMillis, TimeUnit.MILLISECONDS);
    } catch (ThreadInterruptedError | TimedOutError e) {
        // NOSONAR
        future.cancel(true);
        // JUnit timeout exception
        throw new TestTimedOutException(m_timeoutMillis, TimeUnit.MILLISECONDS);
    }
    invoker.throwOnError();
}
Also used : SafeStatementInvoker(org.eclipse.scout.rt.testing.platform.runner.SafeStatementInvoker) ThreadInterruptedError(org.eclipse.scout.rt.platform.util.concurrent.ThreadInterruptedError) TimedOutError(org.eclipse.scout.rt.platform.util.concurrent.TimedOutError) TestTimedOutException(org.junit.runners.model.TestTimedOutException)

Example 17 with ThreadInterruptedError

use of org.eclipse.scout.rt.platform.util.concurrent.ThreadInterruptedError in project scout.rt by eclipse.

the class ClientExceptionHandler method showExceptionInternal.

protected void showExceptionInternal(final Throwable t) {
    final IClientSession session = ClientSessionProvider.currentSession();
    if (session == null) {
        return;
    }
    if (session.getDesktop() == null || !session.getDesktop().isOpened()) {
        return;
    }
    // Prevent loops while displaying the exception.
    final Semaphore loopDetectionSemaphore = getLoopDetectionSemaphore(session);
    if (loopDetectionSemaphore.tryAcquire()) {
        try {
            // Synchronize with the model thread if not applicable.
            if (ModelJobs.isModelThread()) {
                showException(t);
            } else {
                try {
                    ModelJobs.schedule(new IRunnable() {

                        @Override
                        public void run() throws Exception {
                            showException(t);
                        }
                    }, ModelJobs.newInput(ClientRunContexts.copyCurrent()).withExceptionHandling(null, true).withName("Visualizing PlatformException")).awaitDone();
                } catch (final ThreadInterruptedError e) {
                // NOSONAR
                // NOOP
                }
            }
        } finally {
            loopDetectionSemaphore.release();
        }
    } else {
        Exception e = new Exception("Stacktrace and suppressed exception");
        // add original exception for analysis
        e.addSuppressed(t);
        LOG.warn("Loop detection in {}", getClass().getName(), e);
        if (ModelJobs.isModelThread()) {
            IMessageBox msgBox = MessageBoxes.createOk().withSeverity(IStatus.ERROR).withHeader(TEXTS.get("Error"));
            if (t instanceof VetoException) {
                IProcessingStatus status = ((VetoException) t).getStatus();
                msgBox.withHeader(status.getTitle()).withBody(status.getBody());
            }
            msgBox.show();
        }
    }
}
Also used : VetoException(org.eclipse.scout.rt.platform.exception.VetoException) IProcessingStatus(org.eclipse.scout.rt.platform.exception.IProcessingStatus) IClientSession(org.eclipse.scout.rt.client.IClientSession) ThreadInterruptedError(org.eclipse.scout.rt.platform.util.concurrent.ThreadInterruptedError) Semaphore(java.util.concurrent.Semaphore) IRunnable(org.eclipse.scout.rt.platform.util.concurrent.IRunnable) PlatformException(org.eclipse.scout.rt.platform.exception.PlatformException) VetoException(org.eclipse.scout.rt.platform.exception.VetoException) IMessageBox(org.eclipse.scout.rt.client.ui.messagebox.IMessageBox)

Example 18 with ThreadInterruptedError

use of org.eclipse.scout.rt.platform.util.concurrent.ThreadInterruptedError in project scout.rt by eclipse.

the class AbstractPageWithTable method loadChildrenImpl.

/**
 * load tree children<br>
 * this method delegates to the table reload<br>
 * when the table is loaded and this node is not a leaf node then the table rows are mirrored in child nodes
 */
@Override
protected final void loadChildrenImpl() {
    ITree tree = getTree();
    try {
        if (tree != null) {
            tree.setTreeChanging(true);
        }
        // 
        // backup currently selected tree node and its path to root
        boolean oldSelectionOwned = false;
        int oldSelectionDirectChildIndex = -1;
        ITreeNode oldSelectedNode = null;
        if (tree != null) {
            oldSelectedNode = tree.getSelectedNode();
        }
        List<Object> oldSelectedRowKeys = null;
        if (oldSelectedNode != null) {
            ITreeNode t = oldSelectedNode;
            while (t != null && t.getParentNode() != null) {
                if (t.getParentNode() == this) {
                    oldSelectionOwned = true;
                    oldSelectedRowKeys = getTableRowFor(t).getKeyValues();
                    oldSelectionDirectChildIndex = t.getChildNodeIndex();
                    break;
                }
                t = t.getParentNode();
            }
        }
        // 
        setChildrenLoaded(false);
        fireBeforeDataLoaded();
        try {
            loadTableDataImpl();
        } catch (ThreadInterruptedError | FutureCancelledError e) {
        // NOSONAR
        // NOOP
        } finally {
            fireAfterDataLoaded();
        }
        setChildrenLoaded(true);
        setChildrenDirty(false);
        // table events will handle automatic tree changes in case table is mirrored in tree.
        // restore currently selected tree node when it was owned by our table rows.
        // in case selection was lost, try to select similar index as before
        T table = getTable();
        if (tree != null && table != null && oldSelectionOwned && tree.getSelectedNode() == null) {
            ITreeNode newSelectedNode = null;
            ITableRow row = table.getSelectedRow();
            if (row != null) {
                newSelectedNode = getTreeNodeFor(row);
            } else {
                row = table.findRowByKey(oldSelectedRowKeys);
                if (row != null) {
                    newSelectedNode = getTreeNodeFor(row);
                } else if (oldSelectedNode != null && oldSelectedNode.getTree() == tree) {
                    // NOSONAR
                    newSelectedNode = oldSelectedNode;
                } else {
                    int index = Math.max(-1, Math.min(oldSelectionDirectChildIndex, getChildNodeCount() - 1));
                    if (index >= 0 && index < getChildNodeCount()) {
                        newSelectedNode = getChildNode(index);
                    } else {
                        newSelectedNode = this;
                    }
                }
            }
            if (newSelectedNode != null) {
                tree.selectNode(newSelectedNode);
            }
        }
    } finally {
        if (tree != null) {
            tree.setTreeChanging(false);
        }
    }
    IDesktop desktop = ClientSessionProvider.currentSession().getDesktop();
    if (desktop != null) {
        desktop.afterTablePageLoaded(this);
    }
}
Also used : ITreeNode(org.eclipse.scout.rt.client.ui.basic.tree.ITreeNode) FutureCancelledError(org.eclipse.scout.rt.platform.util.concurrent.FutureCancelledError) ThreadInterruptedError(org.eclipse.scout.rt.platform.util.concurrent.ThreadInterruptedError) ITree(org.eclipse.scout.rt.client.ui.basic.tree.ITree) ITableRow(org.eclipse.scout.rt.client.ui.basic.table.ITableRow) IDesktop(org.eclipse.scout.rt.client.ui.desktop.IDesktop)

Example 19 with ThreadInterruptedError

use of org.eclipse.scout.rt.platform.util.concurrent.ThreadInterruptedError in project scout.rt by eclipse.

the class SqlConnectionPool method leaseConnection.

public Connection leaseConnection(AbstractSqlService service) throws ClassNotFoundException, SQLException {
    managePool();
    synchronized (m_poolLock) {
        Assertions.assertFalse(isDestroyed(), "{} not available because destroyed.", getClass().getSimpleName());
        PoolEntry candidate = null;
        while (candidate == null) {
            // get next available conn
            for (Iterator it = m_idleEntries.iterator(); it.hasNext(); ) {
                candidate = (PoolEntry) it.next();
                break;
            }
            if (candidate == null && m_idleEntries.size() + m_busyEntries.size() < m_poolSize) {
                // create new connection
                PoolEntry test = new PoolEntry();
                test.conn = new SqlConnectionBuilder().createJdbcConnection(service);
                LOG.info("created jdbc connection {}", test.conn);
                service.callbackAfterConnectionCreated(test.conn);
                test.createTime = System.currentTimeMillis();
                m_idleEntries.add(test);
                candidate = test;
            }
            if (candidate == null) {
                // wait
                try {
                    m_poolLock.wait();
                } catch (java.lang.InterruptedException ie) {
                    // Restore the thread's interrupted status because cleared by catching {@link java.lang.InterruptedException}.
                    Thread.currentThread().interrupt();
                    throw new ThreadInterruptedError("Interrupted while leasing database connection");
                }
            }
            // test candidate connection
            if (candidate != null) {
                try {
                    service.callbackTestConnection(candidate.conn);
                } catch (Exception e) {
                    // remove candidate from idle pool and close it
                    m_idleEntries.remove(candidate);
                    LOG.warn("closing dirty connection: {}", candidate.conn, e);
                    try {
                        candidate.conn.close();
                    } catch (Exception fatal) {
                        LOG.warn("could not close candidate connection", fatal);
                    }
                    candidate = null;
                }
            }
        }
        // end while
        // move to busy pool
        m_idleEntries.remove(candidate);
        candidate.leaseBegin = System.currentTimeMillis();
        candidate.leaseCount++;
        m_busyEntries.add(candidate);
        LOG.debug("lease   {}", candidate.conn);
        return candidate.conn;
    }
}
Also used : Iterator(java.util.Iterator) ThreadInterruptedError(org.eclipse.scout.rt.platform.util.concurrent.ThreadInterruptedError) SQLException(java.sql.SQLException)

Example 20 with ThreadInterruptedError

use of org.eclipse.scout.rt.platform.util.concurrent.ThreadInterruptedError in project scout.rt by eclipse.

the class BlockingCondition method awaitUntilSignaledOrTimeout.

/**
 * Waits until signaled or the timeout elapses. If <code>awaitInterruptibly</code> is set to <code>true</code>, this
 * method returns with an {@link ThreadInterruptedError} upon interruption. For either case, when this method
 * finally returns, the thread's interrupted status will still be set.
 */
protected void awaitUntilSignaledOrTimeout(final long timeout, final TimeUnit unit, final boolean awaitInterruptibly) {
    boolean interrupted = false;
    m_lock.lock();
    try {
        if (timeout == TIMEOUT_INDEFINITELY) {
            while (m_blocking) {
                // while-loop to address spurious wake-ups
                if (awaitInterruptibly) {
                    m_unblockedCondition.await();
                } else {
                    m_unblockedCondition.awaitUninterruptibly();
                }
            }
        } else {
            long nanos = unit.toNanos(timeout);
            while (m_blocking && nanos > 0L) {
                // while-loop to address spurious wake-ups
                if (awaitInterruptibly) {
                    nanos = m_unblockedCondition.awaitNanos(nanos);
                } else {
                    try {
                        // NOSONAR
                        nanos = m_unblockedCondition.awaitNanos(nanos);
                    } catch (final InterruptedException e) {
                        // remember interruption
                        interrupted = true;
                        // clear the interrupted status to continue waiting
                        Thread.interrupted();
                    }
                }
            }
            if (nanos <= 0L) {
                throw new TimedOutError("Timeout elapsed while waiting for a blocking condition to fall").withContextInfo("blockingCondition", this).withContextInfo("timeout", "{}ms", unit.toMillis(timeout)).withContextInfo("thread", Thread.currentThread().getName());
            }
        }
    } catch (final InterruptedException e) {
        interrupted = true;
        throw new ThreadInterruptedError("Interrupted while waiting for a blocking condition to fall").withContextInfo("blockingCondition", this).withContextInfo("thread", Thread.currentThread().getName());
    } finally {
        m_lock.unlock();
        if (interrupted) {
            // restore interruption status
            Thread.currentThread().interrupt();
        }
    }
}
Also used : ThreadInterruptedError(org.eclipse.scout.rt.platform.util.concurrent.ThreadInterruptedError) TimedOutError(org.eclipse.scout.rt.platform.util.concurrent.TimedOutError)

Aggregations

ThreadInterruptedError (org.eclipse.scout.rt.platform.util.concurrent.ThreadInterruptedError)36 IRunnable (org.eclipse.scout.rt.platform.util.concurrent.IRunnable)20 Test (org.junit.Test)14 BlockingCountDownLatch (org.eclipse.scout.rt.testing.platform.util.BlockingCountDownLatch)13 TimedOutError (org.eclipse.scout.rt.platform.util.concurrent.TimedOutError)8 FutureCancelledError (org.eclipse.scout.rt.platform.util.concurrent.FutureCancelledError)7 AssertionException (org.eclipse.scout.rt.platform.util.Assertions.AssertionException)5 ArrayList (java.util.ArrayList)4 ProcessingException (org.eclipse.scout.rt.platform.exception.ProcessingException)4 ClientRunContext (org.eclipse.scout.rt.client.context.ClientRunContext)3 PlatformException (org.eclipse.scout.rt.platform.exception.PlatformException)3 IBlockingCondition (org.eclipse.scout.rt.platform.job.IBlockingCondition)3 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)2 AtomicReference (java.util.concurrent.atomic.AtomicReference)2 JMSException (javax.jms.JMSException)2 NamingException (javax.naming.NamingException)2 IClientSession (org.eclipse.scout.rt.client.IClientSession)2 IMessageBox (org.eclipse.scout.rt.client.ui.messagebox.IMessageBox)2 RunMonitor (org.eclipse.scout.rt.platform.context.RunMonitor)2 VetoException (org.eclipse.scout.rt.platform.exception.VetoException)2