/* (non-Javadoc)
@see com.abubusoft.kripton.android.sqlite.executors.TaskExecutor#postToMainThread(java.lang.Runnable)
333214
@Override
    public void postToMainThread(Runnable runnable) {
        if (mMainHandler == null) {
            synchronized (mLock) {
                if (mMainHandler == null) {
                    mMainHandler = new Handler(Looper.getMainLooper());
                }
            }
        }
        //noinspection ConstantConditions
        mMainHandler.post(runnable);
    }
523299
public static void postAction (Component source, String command)
    {
        // slip things onto the event queue for later
        ActionEvent event = new ActionEvent(source, 0, command);
        EventQueue.invokeLater(new ActionInvoker(event));
    }
178383
private void tryDispatchBoundaryCallbacks(boolean post) {
        final boolean dispatchBegin = mBoundaryCallbackBeginDeferred
                && mLowestIndexAccessed <= mConfig.prefetchDistance;
        final boolean dispatchEnd = mBoundaryCallbackEndDeferred
                && mHighestIndexAccessed >= size() - 1 - mConfig.prefetchDistance;

        if (!dispatchBegin && !dispatchEnd) {
            return;
        }

        if (dispatchBegin) {
            mBoundaryCallbackBeginDeferred = false;
        }
        if (dispatchEnd) {
            mBoundaryCallbackEndDeferred = false;
        }
        if (post) {
            mMainThreadExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    dispatchBoundaryCallbacks(dispatchBegin, dispatchEnd);
                }
            });
        } else {
            dispatchBoundaryCallbacks(dispatchBegin, dispatchEnd);
        }
    }
1138160
void afterWrite(Runnable task) {
    if (buffersWrites()) {
      for (int i = 0; i < WRITE_BUFFER_RETRIES; i++) {
        if (writeBuffer().offer(task)) {
          scheduleAfterWrite();
          return;
        }
        scheduleDrainBuffers();
      }

      // The maintenance task may be scheduled but not running due to all of the executor's threads
      // being busy. If all of the threads are writing into the cache then no progress can be made
      // without assistance.
      try {
        performCleanUp(task);
      } catch (RuntimeException e) {
        logger.log(Level.SEVERE, "Exception thrown when performing the maintenance task", e);
      }
    } else {
      scheduleAfterWrite();
    }
  }
563170
public void submit(Runnable task)
    {
        queue.add(task);
        while(true)
        {
            long cur = combinedState.get();
            int shutdown = (int)(cur >> 63) & 1;
            if (shutdown != 0)
            {
                throw new RejectedExecutionException("ThreadExecutor is already shutdown");
            }
            int currentThreads = ((int) (cur >> 32)) & 0x7FFFFFFF;
            int sizeMinusIdle = (int)(cur & 0xFFFFFFFFL);
            if (currentThreads < maxThreads && sizeMinusIdle >= 0)
            {
                currentThreads++;
                long next = combineStates(currentThreads, sizeMinusIdle, shutdown);
                if (combinedState.compareAndSet(cur, next))
                {
                    ThreadGroup localThreadGroup = threadGroup;
                    if (localThreadGroup.isDestroyed())
                    {
                        synchronized (this)
                        {
                            if (this.threadGroup.isDestroyed())
                            {
                                localThreadGroup = new ThreadGroup(this.name);
                                this.threadGroup = localThreadGroup;
                            }
                        }
                    }
                    new ExecutorThread(name + "-" + poolNumber + "-" + threadId.incrementAndGet()).start();
                    break;
                }
            }
            else
            {
                sizeMinusIdle++;
                if (trySettingState(cur, currentThreads, sizeMinusIdle, shutdown)) break;
            }
        }
    }
47816
public static void postAction (
        Component source, String command, Object argument)
    {
        // slip things onto the event queue for later
        CommandEvent event = new CommandEvent(source, command, argument);
        EventQueue.invokeLater(new ActionInvoker(event));
    }
985863
void performPostExecute() throws SQLException {

        resultOut.clearLobResults();

        generatedResult = null;

        if (resultIn == null) {
            return;
        }

        Result current = resultIn;

        while (current.getChainedResult() != null) {
            current = current.getUnlinkChainedResult();

            if (current.getType() == ResultConstants.WARNING) {
                SQLWarning w = Util.sqlWarning(current);

                if (rootWarning == null) {
                    rootWarning = w;
                } else {
                    rootWarning.setNextWarning(w);
                }
            } else if (current.getType() == ResultConstants.ERROR) {
                errorResult = current;
            } else if (current.getType() == ResultConstants.DATA) {
                generatedResult = current;
            }
        }

        if (resultIn.isData()) {
            currentResultSet = new JDBCResultSet(connection.sessionProxy,
                    this, resultIn, resultIn.metaData,
                    connection.connProperties);
        }
    }
724011
void startThread() {

        m_reportPanel.setVisible(true);
        m_startPanel.setVisible(false);
        m_report.setVisible(false);
        CmsStaticExportThread thread = new CmsStaticExportThread(A_CmsUI.getCmsObject());
        CmsReportWidget report = new CmsReportWidget(thread);
        report.setHeight("500px");
        report.setWidth("100%");
        m_layout.addComponent(report);
        thread.start();
    }
516553
@SuppressWarnings("unchecked")
    protected void addPostRunDependent(Executable<? extends Indexable> executable) {
        TaskGroup.HasTaskGroup dependency = (TaskGroup.HasTaskGroup) executable;
        this.addPostRunDependent(dependency);
    }
841467
protected void post(Runnable runnable) {
        Ln.d("Message queue is " + messageQueue);

        if (messageQueue == null) {
            return;
        }
        messageQueue.postAtTime(runnable, SystemClock.uptimeMillis());
    }
1358944
protected void postInvoke(Method m, Object [] args, Object retval, Throwable t)
    {
        postInvoke(m, args, retval, t, null, null);
    }
691217
@Override
    protected void doActionsInEventThread() {
        if (component instanceof ComboBox) {
            ((ComboBox<?>) component).getSelectionModel().select(mIndex);
        } else if (component instanceof ListView) {
            ((ListView<?>) component).getSelectionModel().select(mIndex);
        }
    }
56878
public static void cleanupThreadLocals(Thread thread)
   {
      if (!OperatingSystemUtils.isJava8())
      {
         return;
      }
      try
      {
         if (thread != null)
         {
            cleanField(thread, Thread.class.getDeclaredField("threadLocals"));
            cleanField(thread, Thread.class.getDeclaredField("inheritableThreadLocals"));
         }
      }
      catch (Exception e)
      {
         log.log(Level.WARNING, "Failed to cleanup ThreadLocal instances for Thread [" + thread + "]", e);
      }
   }
1157407
@Override
	public Thread newThread(Runnable runnable) {
		Thread t = new Thread(group, runnable, namePrefix + threadNumber.getAndIncrement());
		t.setDaemon(true);

		t.setPriority(threadPriority);

		// optional handler for uncaught exceptions
		if (exceptionHandler != null) {
			t.setUncaughtExceptionHandler(exceptionHandler);
		}

		return t;
	}
792472
private void cmdExecuteQueryActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_buttonExecuteActionPerformed
		try {
			// TODO Handle this such that there is a listener checking the progress of the execution
			Thread queryRunnerThread = new Thread(() -> {
				String queryString = queryTextPane.getText();
                OBDADataQueryAction<?> action = null;
				if (queryString.isEmpty()){
					JOptionPane.showMessageDialog(QueryInterfacePanel.this, "Query editor cannot be empty.");
				} else if (SPARQLQueryUtility.isSelectQuery(queryString)) {
					action = QueryInterfacePanel.this.getExecuteSelectAction();
				} else if (SPARQLQueryUtility.isAskQuery(queryString)){
					action = QueryInterfacePanel.this.getExecuteAskAction();
                } else if ((SPARQLQueryUtility.isConstructQuery(queryString) || SPARQLQueryUtility.isDescribeQuery(queryString)) ){
                    action = QueryInterfacePanel.this.getExecuteGraphQueryAction();
                } else {
                    JOptionPane.showMessageDialog(QueryInterfacePanel.this, "This type of SPARQL expression is not handled. Please use SELECT, ASK, DESCRIBE, or CONSTRUCT.");
                }
				if(action!=null) {
					action.run(queryString);
					execTime = action.getExecutionTime();
					do {
						int rows = action.getNumberOfRows();
						updateStatus(rows);
						try {
							Thread.sleep(100);
						} catch (InterruptedException e) {
							break;
						}
					} while (action.isRunning());
					int rows = action.getNumberOfRows();
						updateStatus(rows);

				}
            });
			queryRunnerThread.start();
		} catch (Exception e) {
			DialogUtils.showQuickErrorDialog(QueryInterfacePanel.this, e);
		}
	}
76937
public static void invokeOnEventDispatchThread(Runnable runnable)
    {
        if (SwingUtilities.isEventDispatchThread())
        {
            runnable.run();
        }
        else
        {
            SwingUtilities.invokeLater(runnable);
        }
    }
1132807
@Override
    public Thread newThread(final Runnable runnable) {
        int threadId = createdThreadCount.incrementAndGet();
        final String name = executorName + "-thread-" + threadId;
        // The AccessControlContext is implicitly copied from the creating
        // thread, so use doPrivileged to prevent that.
        return AccessController.doPrivileged(new PrivilegedAction<Thread>() {
            @Override
            public Thread run() {
                final Thread thread;
                if (TRACE_ENABLED_AT_STARTUP) {
                    // We don't want a mixed pool of LibertyThreads and regular Threads, which
                    // could occur if a user were to change the trace settings after startup.
                    // Also, using the LibertyThread will have a (very) slight impact on 
                    // performance as it will require a check to the trace component and an
                    // additional method call.  As such, we will only use LibertyThreads if
                    // the trace was enabled at server startup - the user can subsequently
                    // disable the trace while the server is still up, which will stop the
                    // LibertyThreads from printing stack traces, but may still be slightly
                    // slower than using normal Threads.
                    thread = new LibertyThread(threadGroup, runnable, name);
                } else {
                    thread = new Thread(threadGroup, runnable, name);
                }
                // The daemon, priority, and context class loader are implicitly
                // copied from the creating thread, so reset them all.
                thread.setDaemon(true);
                thread.setPriority(Thread.NORM_PRIORITY);
                thread.setContextClassLoader(contextClassLoader);
                return thread;
            }
        });
    }