Perform the given work with a Jedis connection from the given pool.
Wraps any thrown checked exceptions in a RuntimeException.

@param pool the resource pool
@param work the work to perform
@param <V>  the result type
@return the result of the given work
182793
public static <V> V doWorkInPoolNicely(final Pool<Jedis> pool, final PoolWork<Jedis, V> work) {
        final V result;
        try {
            result = doWorkInPool(pool, work);
        } catch (RuntimeException re) {
            throw re;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return result;
    }
411192
public static ThreadPoolExecutor getAsyncThreadPool(boolean build) {
        if (asyncThreadPool == null && build) {
            synchronized (AsyncRuntime.class) {
                if (asyncThreadPool == null && build) {
                    // 一些系统参数，可以从配置或者注册中心获取。
                    int coresize = RpcConfigs.getIntValue(RpcOptions.ASYNC_POOL_CORE);
                    int maxsize = RpcConfigs.getIntValue(RpcOptions.ASYNC_POOL_MAX);
                    int queuesize = RpcConfigs.getIntValue(RpcOptions.ASYNC_POOL_QUEUE);
                    int keepAliveTime = RpcConfigs.getIntValue(RpcOptions.ASYNC_POOL_TIME);

                    BlockingQueue<Runnable> queue = ThreadPoolUtils.buildQueue(queuesize);
                    NamedThreadFactory threadFactory = new NamedThreadFactory("RPC-CB", true);

                    RejectedExecutionHandler handler = new RejectedExecutionHandler() {
                        private int i = 1;

                        @Override
                        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                            if (i++ % 7 == 0) {
                                i = 1;
                                if (LOGGER.isWarnEnabled()) {
                                    LOGGER.warn("Task:{} has been reject because of threadPool exhausted!" +
                                        " pool:{}, active:{}, queue:{}, taskcnt: {}", r,
                                        executor.getPoolSize(),
                                        executor.getActiveCount(),
                                        executor.getQueue().size(),
                                        executor.getTaskCount());
                                }
                            }
                            throw new RejectedExecutionException("Callback handler thread pool has bean exhausted");
                        }
                    };
                    asyncThreadPool = ThreadPoolUtils.newCachedThreadPool(
                        coresize, maxsize, keepAliveTime, queue, threadFactory, handler);
                }
            }
        }
        return asyncThreadPool;
    }
989730
def _work_function(job_q: Queue, result_q: Queue, error_q: Queue) -> None:
    
    while True:
        job = job_q.get()

        if isinstance(job, _ThreadPoolSentinel):
            # All the work is done, get out
            result_q.put(_ThreadPoolSentinel())
            error_q.put(_ThreadPoolSentinel())
            job_q.task_done()
            break

        work_function = job[0]
        args = job[1]
        try:
            result = work_function(*args)
        except Exception as e:
            error_q.put((job, e))
        else:
            result_q.put((job, result))
        finally:
            job_q.task_done()
462191
@Override
    public void run() {
        if (this.state.compareAndSet(NEW, RUNNING)) {
            try {
                renameThread("RUNNING");
                this.threadRef.set(Thread.currentThread());
                PoolUtils.doWorkInPool(this.jedisPool, new PoolWork<Jedis, Void>() {
                    /**
                     * {@inheritDoc}
                     */
                    @Override
                    public Void doWork(final Jedis jedis) throws IOException {
                        jedis.sadd(key(WORKERS), name);
                        jedis.set(key(WORKER, name, STARTED), new SimpleDateFormat(DATE_FORMAT).format(new Date()));
                        listenerDelegate.fireEvent(WORKER_START, WorkerPoolImpl.this, null, null, null, null, null);
                        loadRedisScripts(jedis);
                        return null;
                    }
                });
                poll();
            } catch (Exception ex) {
                LOG.error("Uncaught exception in worker run-loop!", ex);
                this.listenerDelegate.fireEvent(WORKER_ERROR, this, null, null, null, null, ex);
            } finally {
                renameThread("STOPPING");
                this.listenerDelegate.fireEvent(WORKER_STOP, this, null, null, null, null, null);
                PoolUtils.doWorkInPoolNicely(this.jedisPool, new PoolWork<Jedis, Void>() {
                    /**
                     * {@inheritDoc}
                     */
                    @Override
                    public Void doWork(final Jedis jedis) {
                        jedis.srem(key(WORKERS), name);
                        jedis.del(key(WORKER, name), key(WORKER, name, STARTED), key(STAT, FAILED, name),
                                key(STAT, PROCESSED, name));
                        return null;
                    }
                });
                this.threadRef.set(null);
            }
        } else if (RUNNING.equals(this.state.get())) {
            throw new IllegalStateException("This WorkerImpl is already running");
        } else {
            throw new IllegalStateException("This WorkerImpl is shutdown");
        }
    }
728658
@Override
	public JobExecutionResult execute(String jobName) throws Exception {
		PlanExecutor executor = getExecutor();

		Plan p = createProgramPlan(jobName);

		// Session management is disabled, revert this commit to enable
		//p.setJobId(jobID);
		//p.setSessionTimeout(sessionTimeout);

		JobExecutionResult result = executor.executePlan(p);

		this.lastJobExecutionResult = result;
		return result;
	}
1081768
public ConnectionPool getPool(String poolName)
            throws ConnectionPoolNotFoundException {
        ConnectionPool connectionPool = null;

        try {
            if (h_ConnectionPools.containsKey(poolName)) {
                connectionPool = h_ConnectionPools.get(poolName);
            } else {
                // Error: pool was never initialized or name could not be found
                throw new ConnectionPoolNotFoundException("Connection pool "
                        + "not found: " + poolName);
            }
        } catch (Throwable th) {
            throw new ConnectionPoolNotFoundException("The specified connection "
                    + "pool \""
                    + poolName
                    + "\" could not be found. The underlying "
                    + "error was a "
                    + th.getClass().getName()
                    + "The message was \""
                    + th.getMessage() + "\".");
        }

        return connectionPool;
    }
348159
protected JedisClientPool createRedisClientPool(String host, int port, String username,
            String password) {
        return createRedisClientPool(host, port, username, password, null);
    }
231387
private Throwable getResult(FutureTask<Throwable> task, Thread thread) {
        try {
            if (timeout > 0) {
                return task.get(timeout, timeUnit);
            } else {
                return task.get();
            }
        } catch (InterruptedException e) {
            return e; // caller will re-throw; no need to call Thread.interrupt()
        } catch (ExecutionException e) {
            // test failed; have caller re-throw the exception thrown by the test
            return e.getCause();
        } catch (TimeoutException e) {
            return createTimeoutException(thread);
        }
    }
893995
public Stage rerunFailedJobs(final Stage stage, final HttpOperationResult result) {
        final StageIdentifier identifier = stage.getIdentifier();
        JobInstances jobInstances = stage.jobsWithResult(JobResult.Cancelled, JobResult.Failed);
        List<String> jobNames = jobInstances.stream().map(JobInstance::getName).collect(Collectors.toList());

        if (jobNames.isEmpty()) {
            String message = "There are no failed jobs in the stage that could be re-run";
            result.badRequest(message, message, HealthStateType.general(HealthStateScope.forStage(identifier.getPipelineName(), identifier.getStageName())));
            return null;
        }
        return rerunJobs(stage, jobNames, result);
    }
1096666
public final void setWork(final long work) {
    if (getWork() != WORK_UNKNOWN) {
      throw new IllegalStateException("Cannot set work amount if it was already previously specified");
    }
    new JAtomic() {
      @Override boolean abort(Job job) { return false; }
      @Override void update(Job old) { old._work = work; }
    }.apply(this);
  }
1306651
protected void failure(final Throwable thrwbl, final Job job, final String curQueue) {
        try {
            PoolUtils.doWorkInPool(this.jedisPool, new PoolWork<Jedis, Void>() {
                /**
                 * {@inheritDoc}
                 */
                @Override
                public Void doWork(final Jedis jedis) throws IOException {
                    jedis.incr(key(STAT, FAILED));
                    jedis.incr(key(STAT, FAILED, name));
                    final FailQueueStrategy strategy = failQueueStrategyRef.get();
                    final String failQueueKey = strategy.getFailQueueKey(thrwbl, job, curQueue);
                    if (failQueueKey != null) {
                        final int failQueueMaxItems = strategy.getFailQueueMaxItems(curQueue);
                        if (failQueueMaxItems > 0) {
                            Long currentItems = jedis.llen(failQueueKey);
                            if (currentItems >= failQueueMaxItems) {
                                Transaction tx = jedis.multi();
                                tx.ltrim(failQueueKey, 1, -1);
                                tx.rpush(failQueueKey, failMsg(thrwbl, curQueue, job));
                                tx.exec();
                            } else {
                                jedis.rpush(failQueueKey, failMsg(thrwbl, curQueue, job));
                            }
                        } else {
                            jedis.rpush(failQueueKey, failMsg(thrwbl, curQueue, job));
                        }
                    }
                    return null;
                }
            });
        } catch (JedisException je) {
            LOG.warn("Error updating failure stats for throwable=" + thrwbl + " job=" + job, je);
        } catch (IOException ioe) {
            LOG.warn("Error serializing failure payload for throwable=" + thrwbl + " job=" + job, ioe);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        this.listenerDelegate.fireEvent(JOB_FAILURE, this, curQueue, job, null, null, thrwbl);
    }
807894
public void returnToResultPool(Result result) {
        if (result != null) {
            result.reset();
            resultPool.add(result);
        }
    }
1069531
private Connection<CL> getConnectionForTokenOnRackNoFallback(BaseOperation<CL, ?> op, Long token, String rack, int duration, TimeUnit unit, RetryPolicy retry)
            throws NoAvailableHostsException, PoolExhaustedException, PoolTimeoutException, PoolOfflineException {
        DynoConnectException lastEx = null;

        // find the selector for that rack,
		HostSelectionStrategy<CL> selector = findSelectorForRack(rack);
		// get the host using that selector
		HostConnectionPool<CL>  hostPool = selector.getPoolForToken(token);

        if (hostPool != null) {
            try {
                // Note that if a PoolExhaustedException is thrown it is caught by the calling
                // ConnectionPoolImpl#executeXXX() method
                return hostPool.borrowConnection(duration, unit);
            } catch (PoolTimeoutException pte) {
                lastEx = pte;
                cpMonitor.incOperationFailure(null, pte);
            }
        }

        if (lastEx == null) {
            throw new PoolOfflineException(hostPool == null ? null : hostPool.getHost(), "host pool is offline and we are forcing no fallback");
        } else {
            throw lastEx;
        }
    }
659733
@CheckReturnValue
  public static Builder fromPool(Pool pool) {
    return new BuilderImpl(pool.poolShutdown, () -> {
      try {
        return pool.dataSource.getConnection();
      } catch (Exception e) {
        throw new DatabaseException("Unable to obtain a connection from the DataSource", e);
      }
    }, new OptionsDefault(pool.flavor));
  }
1349320
public V get(ResourceType type, String poolGroupName) {
    Map<String, V> poolGroupNameMap = typePoolGroupNameMap.get(type);
    if (poolGroupNameMap == null) {
      return null;
    }
    return poolGroupNameMap.get(poolGroupName);
  }
5915
public QueryResults execute() throws JspCoreException, SQLException {

        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        ;
        QueryResults qs = null;
        // verify all parameters
        verify();

        // invoke the compute method of QueryResults passing it the SQL resultset
        // the QueryResults will get all the data from the result set and cache it in
        // its private datastructures
        try {
            conn = getJdbcConnection();
            //conn = DriverManager.getConnection(url,user,passwd);
            stmt = conn.createStatement();
            int mrows = getMaxRows();
            if (mrows > 0)
                stmt.setMaxRows(mrows);
            rs = stmt.executeQuery(getQueryString());
            qs = new QueryResults();
            qs.compute(rs);
        }
        catch (SQLException e) {
            //com.ibm.ws.ffdc.FFDCFilter.processException(e, "com.ibm.ws.webcontainer.jsp.tsx.db.Query.execute", "73", this);
            throw e;
        }
        finally { // always free up database resources
            if (rs != null)
                rs.close();
            if (stmt != null)
                stmt.close();
            if (conn != null)
                conn.close();
        }
        setResults(qs);
        return qs;
    }
87208
public static IPool getPool(String host, Integer port, String database, String... userPwd) {
        //暂未启用
        throw new RuntimeException("未找到指定的数据库连接池");
    }