public static FarmDomain getInstance() { if (null == farmDomain || null == farmDomain.get()) { farmDomain = new ThreadLocal<FarmDomain>(); farmDomain.set(new FarmDomain()); } return farmDomain.get(); }
public Object getObject() throws Exception { if (isFetchingService.get()) return null; // we already have been invoked, don't recurse, just return null. isFetchingService.set(true); try { Object service = null; if (StringUtils.isBlank(getServiceNamespace())) { service = GlobalResourceLoader.getService(this.getServiceName()); } else { service = GlobalResourceLoader.getService(new QName(getServiceNamespace(), getServiceName())); } if (mustExist && service == null) { throw new IllegalStateException( "Service must exist and no service could be located with serviceNamespace='" + getServiceNamespace() + "' and name='" + this.getServiceName() + "'"); } return service; } finally { isFetchingService.remove(); } }
public static void rollbackTransaction() throws Exception { if (tranConnection.get() == null) { throw new Exception("Can't rollback: this thread isn't currently in a " + "transaction"); } tranConnection.get().rollback(); tranConnection.set(null); }
public void lock() { QNode node = myNode.get(); node.locked = true; QNode pred = tail.getAndSet(node); myPred.set(pred); while (pred.locked) {} }
private static CascadingTx createTransaction(final Object obj) throws RecoverablePersistenceException, RuntimeException { final String ctx = lookatPersistenceContext(obj); final CascadingTx ret = new CascadingTx(ctx); try { ret.begin(); if (txRootThreadLocal.get() == null) { final String txId = makeTxRootName(ret); LOG.trace( "Creating root entry for transaction tree: " + txId + " at: \n" + Threads.currentStackString()); txRootThreadLocal.set(txId); } txStateThreadLocal.get().put(ctx, ret); return ret; } catch (RuntimeException ex) { try { ret.rollback(); } catch (RuntimeException ex1) { throw ex1; } throw ex; } }
@Override public ProcessingItem[] process(final CompileContext context, final ProcessingItem[] items) { context.getProgressIndicator().setText(myValidator.getProgressIndicatorText()); final List<ProcessingItem> processedItems = new ArrayList<ProcessingItem>(); final List<LocalInspectionTool> inspections = new ArrayList<LocalInspectionTool>(); for (final Class aClass : myValidator.getInspectionToolClasses(context)) { try { inspections.add((LocalInspectionTool) aClass.newInstance()); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new Error(e); } } for (int i = 0; i < items.length; i++) { final MyValidatorProcessingItem item = (MyValidatorProcessingItem) items[i]; context.getProgressIndicator().checkCanceled(); context.getProgressIndicator().setFraction((double) i / items.length); try { ourCompilationThreads.set(Boolean.TRUE); if (checkFile(inspections, item, context)) { processedItems.add(item); } } finally { ourCompilationThreads.set(Boolean.FALSE); } } return processedItems.toArray(new ProcessingItem[processedItems.size()]); }
// YYYY = four-digit year // MM = two-digit month (01=January, etc.) // DD = two-digit day of month (01 through 31) // hh = two digits of hour (00 through 23) (am/pm NOT allowed) // mm = two digits of minute (00 through 59) // ss = two digits of second (00 through 59) // s = one or more digits representing a decimal fraction of a second // TZD = time zone designator (Z or +hh:mm or -hh:mm) public static Date parse(String input) throws java.text.ParseException { // NOTE: SimpleDateFormat uses GMT[-+]hh:mm for the TZ which breaks // things a bit. Before we go on we have to repair this. // this is zero time so we need to add that TZ indicator for if (input.endsWith("Z")) { input = input.substring(0, input.length() - 1) + "GMT-00:00"; } else { final int inset = 6; final String s0 = input.substring(0, input.length() - inset); final String s1 = input.substring(input.length() - inset, input.length()); input = s0 + "GMT" + s1; } try { return normalDf.get().parse(input); } catch (ParseException e) { // modification by gnip4j. the data collector (at least with // facebook feed) sends // some date with - in the time part. return hackDf.get().parse(input); } }
// private synchronized boolean makeWithdrawal(int withdrawalAmount) { private synchronized void makeWithdrawal(int withdrawalAmount) { if (account.getAccountBalance() >= withdrawalAmount) { System.out.println("\n+ Account balance is sufficient enough to make a withdrawl..."); System.out.println(Thread.currentThread().getName() + " is about to make an withdrawal."); Random random = new Random(); int sleepTime = random.nextInt(500) + 510; System.out.println("+ Sleeping for - " + sleepTime); // Thread.sleep(sleepTime); System.out.println( "+ Wake-up Call - " + Thread.currentThread().getName() + " just WOKE UP..."); TOTAL_WITHDRAWN.set(TOTAL_WITHDRAWN.get() + account.withdrawal(10)); System.out.println( "+ Total Withdrawal by " + Thread.currentThread().getName() + " = " + TOTAL_WITHDRAWN.get()); System.out.println("+ Account Balance = " + account.getAccountBalance() + "\n"); } else { System.out.println( "+ WARNING: Sorry " + Thread.currentThread().getName() + ", insufficient account balance!!!"); } }
@Deprecated public static void clear() { GlobalVariables.clear(); messageLists.set(new MessageList()); auditErrorMaps.set(new HashMap<String, AuditCluster>()); kualiForms.set(null); }
@Override protected void doBeginRead() throws Exception { if (readInProgress) { return; } ChannelPipeline pipeline = pipeline(); Queue<Object> inboundBuffer = this.inboundBuffer; if (inboundBuffer.isEmpty()) { readInProgress = true; return; } final Integer stackDepth = READER_STACK_DEPTH.get(); if (stackDepth < MAX_READER_STACK_DEPTH) { READER_STACK_DEPTH.set(stackDepth + 1); try { for (; ; ) { Object received = inboundBuffer.poll(); if (received == null) { break; } pipeline.fireChannelRead(received); } pipeline.fireChannelReadComplete(); } finally { READER_STACK_DEPTH.set(stackDepth); } } else { eventLoop().execute(readTask); } }
public static String formatFileTime(long time, Context context) { Date currentDate = new Date(System.currentTimeMillis()); Date convertableDate = new Date(time); String convertedDate = dateInstanceGetter.get().format(convertableDate); String convertedTime = timeInstanceGetter.get().format(convertableDate); /*if (currentDate.getYear() == convertableDate.getYear()) { if (currentDate.getMonth() == convertableDate.getMonth()) { if (currentDate.getDay() == convertableDate.getDay()) { if (currentDate.getHours() == convertableDate.getHours()) { if (currentDate.getMinutes() == convertableDate.getMinutes()) { return context.getString(R.string.picker_time_minute_ago); } int minutesAgo = currentDate.getMinutes() - convertableDate.getMinutes(); return context.getResources().getQuantityString(R.plurals.picker_time_minutes_ago, minutesAgo, minutesAgo); // to do android-i18n-plurals implementation } else { if (currentDate.getHours() - 1 == convertableDate.getHours()) { return context.getString(R.string.picker_time_hour_ago); } } return context.getString(R.string.picker_time_today_at, convertedTime); } else { if (currentDate.getDay() - 1 == convertableDate.getDay()) { return context.getString(R.string.picker_time_yesterday_at, convertedTime); } } } int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_NO_YEAR; convertedDate = DateUtils.formatDateTime(context, time, flags); }*/ return context.getString(R.string.picker_time_at, convertedDate, convertedTime); }
protected SmiMib getMib() { // this is a rather ugly hack to mimic JUnit4 @BeforeClass, without having to annotate all test // methods: if (m_mib.get() == null || m_testClass.get() != getClass()) { try { SmiParser parser = createParser(); StopWatch stopWatch = new StopWatch(); stopWatch.start(); SmiMib mib = parser.parse(); stopWatch.stop(); m_log.info("Parsing time: " + stopWatch.getTotalTimeSeconds() + " s"); if (mustParseSuccessfully()) { assertTrue(((SmiDefaultParser) parser).getProblemEventHandler().isOk()); assertEquals( 0, ((SmiDefaultParser) parser) .getProblemEventHandler() .getSeverityCount(ProblemSeverity.ERROR)); } m_mib.set(mib); m_testClass.set(getClass()); } catch (Exception e) { throw new RuntimeException(e); } } return m_mib.get(); }
public static void setContext(LocalContext aContext) { if (aContext != null) { contextRef.set(aContext); } else { contextRef.remove(); } }
public long count(final String queryString, final Object... values) { String tmp = queryString.toLowerCase().replaceAll("\\s+", " "); if (!tmp.contains("group by") && !tmp.contains("distinct")) { String countQueryString = "select count(*) " + queryString.substring(queryString.indexOf("from ")); return (Long) queryUnique(countQueryString, values); } QueryTranslatorImpl queryTranslator = new QueryTranslatorImpl( null, queryString, Collections.EMPTY_MAP, (SessionFactoryImplementor) sessionFactory); queryTranslator.compile(Collections.EMPTY_MAP, false); final String countQueryString = "select count(*) as result from (" + queryTranslator.getSQLString() + ")"; SQLQuery query = getSession().createSQLQuery(countQueryString); if (cacheRegion.get() != null) { // TODO // SQLQuery遭遇UpdateTimestampsCache时,有问题。详见:http://raymondhekk.iteye.com/blog/250427 // 故这里暂停使用二级缓存 // query.setCacheRegion(cacheRegion.get()); // query.setCacheable(true); cacheRegion.set(null); } for (int position = 0; position < values.length; position++) { query.setParameter(position, values[position]); } query.addScalar("result", StandardBasicTypes.BIG_DECIMAL); return ((Number) query.uniqueResult()).longValue(); }
/** * Execute schema creation script, determined by the Configuration object used for creating the * SessionFactory. A replacement for Hibernate's SchemaValidator class, to be invoked after * application startup. * * <p>Fetch the LocalSessionFactoryBean itself rather than the exposed SessionFactory to be able * to invoke this method, e.g. via {@code LocalSessionFactoryBean lsfb = (LocalSessionFactoryBean) * ctx.getBean("&mySessionFactory");}. * * <p>Uses the SessionFactory that this bean generates for accessing a JDBC connection to perform * the script. * * @throws DataAccessException in case of script execution errors * @see org.hibernate.cfg.Configuration#validateSchema * @see org.hibernate.tool.hbm2ddl.SchemaValidator */ public void validateDatabaseSchema() throws DataAccessException { logger.info("Validating database schema for Hibernate SessionFactory"); DataSource dataSource = getDataSource(); if (dataSource != null) { // Make given DataSource available for the schema update. configTimeDataSourceHolder.set(dataSource); } try { SessionFactory sessionFactory = getSessionFactory(); final Dialect dialect = ((SessionFactoryImplementor) sessionFactory).getDialect(); HibernateTemplate hibernateTemplate = new HibernateTemplate(sessionFactory); hibernateTemplate.setFlushMode(HibernateTemplate.FLUSH_NEVER); hibernateTemplate.execute( new HibernateCallback<Object>() { @Override public Object doInHibernate(Session session) throws HibernateException, SQLException { Connection con = session.connection(); DatabaseMetadata metadata = new DatabaseMetadata(con, dialect, false); getConfiguration().validateSchema(dialect, metadata); return null; } }); } finally { if (dataSource != null) { configTimeDataSourceHolder.remove(); } } }
public static void main(String[] args) { if (tl.get() == null) { System.out.println("线程变量中没有值"); tl.set("设置main线程中的变量值"); } System.out.println(tl.get()); }
/** 这是我们所有的线程都调用的模型函数 */ static synchronized void compute() { // 计算出已经被当前线程调用的次数 Integer n = (Integer) numcalls.get(); if (n == null) n = new Integer(1); else n = new Integer(n.intValue() + 1); numcalls.set(n); // 显示线程的名字和调用的次数 System.out.println(Thread.currentThread().getName() + ": " + n); // 做一个长时间的计算,模拟一个有限次计算的线程 for (int i = 0, j = 0; i < 1000000; ++i) j += i; // 同样的,我们可以通过使线程休眠一段任意的时间来模拟一个 // 线程因为网络或者I/O操作的延迟 try { Thread.sleep((int) (Math.random() * 100 + 1)); } catch (InterruptedException e) { } // 每一个线程都客气的给其它线程提供运行的机会,这是很 // 重要的,可以保证一个线程不会使同等优先级的线程饿死 Thread.yield(); }
@Override protected URL buildUrl(String resource, String query) throws URISyntaxException, MalformedURLException { int uriport = 0; if ("http".equals(proto) && port == 80) { // Default port uriport = -1; } else if ("https".equals(proto) && port == 443) { uriport = -1; } else { uriport = port; } String host = null; if (mode == LBMode.ROUND_ROBIN_THREADS) { // Bind thread to a specific host if (threadHost.get() == null) { threadHost.set(hosts.get((int) (requestCount++ % hosts.size()))); l4j.info("Thread bound to " + threadHost.get()); } host = threadHost.get(); } else { host = hosts.get((int) (requestCount++ % hosts.size())); } URI uri = new URI(proto, null, host, uriport, resource, query, null); URL u = uri.toURL(); l4j.debug("URL: " + u); return u; }
/** * Tries to call the given consistent operation while holding the given lock. * * <p>If this is the first execution of this method on the call stack of the current thread, then * the lock gets acquired using {@link Lock#lock()}. Once the lock has been acquired the operation * gets called. If this fails for some reason and the thrown exception chain contains a {@link * FsNeedsLockRetryException}, then the lock gets temporarily released and the current thread gets * paused for a small random time interval before this procedure starts over again. Otherwise, the * exception chain gets just passed on to the caller. * * <p>If this is <em>not</em> the first execution of this method on the call stack of the current * thread, then the lock gets acquired using {@link Lock#tryLock()} instead. If this fails, an * {@code FsNeedsLockRetryException} gets created and passed to the given exception handler for * mapping before finally throwing the resulting exception by executing {@code throw * handler.fail(new FsNeedsLockRetryException())}. Once the lock has been acquired the operation * gets called. If this fails for some reason then the exception chain gets just passed on to the * caller. * * <p>This algorithm prevents dead locks effectively by temporarily unwinding the stack and * releasing all locks for a small random time interval. Note that this requires some minimal * cooperation by the operation: Whenever it throws an exception, it MUST leave its resources in a * consistent state so that it can get retried again! Mind that this is standard requirement for * any {@link FsController}. * * @param <T> The return type of the operation. * @param operation The atomic operation. * @param lock The lock to hold while calling the operation. * @return The result of the operation. * @throws IOException As thrown by the operation. * @throws FsNeedsLockRetryException See above. */ private <T> T locked(final Operation<T> operation, final Lock lock) throws IOException { final Account account = accounts.get(); if (0 < account.lockCount) { if (!lock.tryLock()) throw FsNeedsLockRetryException.get(); account.lockCount++; try { return operation.call(); } finally { account.lockCount--; lock.unlock(); } } else { try { while (true) { try { lock.lock(); account.lockCount++; try { return operation.call(); } finally { account.lockCount--; lock.unlock(); } } catch (FsNeedsLockRetryException ex) { account.pause(); } } } finally { accounts.remove(); } } }
/** * Open a connection for the current thread. * * @return A valid SQL connection */ @SuppressWarnings("deprecation") public Connection getConnection() { try { // do we have a present JPAContext for this db-config in current thread? JPAConfig jpaConfig = JPA.getJPAConfig(dbConfigName); if (jpaConfig != null) { JPAContext jpaContext = jpaConfig.getJPAContext(); return ((org.hibernate.ejb.EntityManagerImpl) jpaContext.em()).getSession().connection(); } // do we have a current raw connection bound to thread? if (localConnection.get() != null) { return localConnection.get(); } // must create connection Connection connection = datasource.getConnection(); localConnection.set(connection); return connection; } catch (SQLException ex) { throw new DatabaseException("Cannot obtain a new connection (" + ex.getMessage() + ")", ex); } catch (NullPointerException e) { if (datasource == null) { throw new DatabaseException( "No database found. Check the configuration of your application.", e); } throw e; } }
/** * Opens new session or returns currently open session for this thread. * * @return session object. * @throws HibernateException if something with session creation goes wrong. */ public static Session openSession() throws HibernateException { if (!inited) init(); Session s = SESSION.get(); if (s != null) { LOG.log( Level.WARNING, "Openning session more than once from the same thread!", new Exception("Dump")); s.clear(); return s; } else { try { lock.lock(); } catch (InterruptedException e) { throw new RuntimeException("Interrupted waiting for session."); } s = sessionHandler.getSession(); SESSION.set(s); } return s; }
public void actionHandler(SelectionKey key) throws IOException { if (key.isAcceptable()) { ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel(); SocketChannel socketChannel = serverChannel.accept(); socketChannel.configureBlocking(false); socketChannel.register(roller, SelectionKey.OP_READ); } else if (key.isReadable()) { ByteBuffer buffer = ByteBuffer.allocate(16); SocketChannel socketChannel = (SocketChannel) key.channel(); socketChannel.read(buffer); buffer.flip(); String temp = decode(buffer); StringBuffer strBuffer = stringLocal.get(); if (strBuffer == null) { strBuffer = new StringBuffer(); } strBuffer.append(temp); if (temp.equals("\r\n")) { System.out.println(strBuffer.toString()); strBuffer = null; } stringLocal.set(strBuffer); } }
public static FTPClient getFTPClient() { FTPClient client = ftpClientThreadLocal.get(); if (client != null && client.isConnected()) { return client; } ftpClientThreadLocal.remove(); FTPClient ftpClient = new FTPClient(); // 创建ftpClient ftpClient.setControlEncoding("UTF-8"); // 设置字符编码 Boolean isConnect = connectFtp(ftpClient); ftpClient.enterLocalPassiveMode(); try { ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); ftpClient.setSoTimeout(1000 * 30); } catch (Exception e) { e.printStackTrace(); } // 得到返回答复码 int reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { try { ftpClient.disconnect(); } catch (IOException e) { e.printStackTrace(); } } else { ftpClientThreadLocal.set(ftpClient); } return ftpClient; }
static DecimalFormat getDecimalFormat(int padding) { if (padding > 14) { // FieldConvertError not supported in setDouble methods on Message throw new RuntimeError("maximum padding of 14 zeroes is supported: " + padding); } DecimalFormat[] decimalFormats = THREAD_DECIMAL_FORMATS.get(); if (decimalFormats == null) { decimalFormats = new DecimalFormat[14]; THREAD_DECIMAL_FORMATS.set(decimalFormats); } DecimalFormat f = decimalFormats[padding]; if (f == null) { StringBuilder buffer = new StringBuilder("0."); for (int i = 0; i < padding; i++) { buffer.append('0'); } for (int i = padding; i < 14; i++) { buffer.append('#'); } f = new DecimalFormat(buffer.toString()); f.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US)); decimalFormats[padding] = f; } return f; }
@Override protected void run() { // Fetch the globals, which includes a reference to the root // type. References to other objects can't be resolved, // because the type definitions haven't been loaded yet. refreshGlobals(); ObjectType rootType = getRootType(); if (rootType != null) { // This isn't cleared later, because that's done within // {@link refreshTypes} anyway. TypesCache temporaryTypes = temporaryTypesLocal.get(); if (temporaryTypes == null) { temporaryTypes = new TypesCache(); temporaryTypesLocal.set(temporaryTypes); } temporaryTypes.add(rootType); LOGGER.info("Root type ID for [{}] is [{}]", getDatabase().getName(), rootType.getId()); } // Load all other types based on the root type. Then globals // again in case they reference other typed objects. Then // types again using the information from the fully resolved // globals. refreshTypes(); refreshGlobals(); refreshTypes(); refresher.scheduleWithFixedDelay(5.0, 5.0); }
public JSONReaderScanner(Reader reader, int features) { super(features); this.reader = reader; buf = BUF_LOCAL.get(); if (buf != null) { BUF_LOCAL.set(null); } if (buf == null) { buf = new char[1024 * 8]; } try { bufLength = reader.read(buf); } catch (IOException e) { throw new JSONException(e.getMessage(), e); } bp = -1; next(); if (ch == 65279) { // utf8 bom next(); } }
/** get a connection */ public static Connection getConnection() throws Exception { if (tranConnection.get() != null) { return tranConnection.get(); } else { return eds.getConnection(); } }
/** * Execute schema creation script, determined by the Configuration object used for creating the * SessionFactory. A replacement for Hibernate's SchemaExport class, to be invoked on application * setup. * * <p>Fetch the LocalSessionFactoryBean itself rather than the exposed SessionFactory to be able * to invoke this method, e.g. via {@code LocalSessionFactoryBean lsfb = (LocalSessionFactoryBean) * ctx.getBean("&mySessionFactory");}. * * <p>Uses the SessionFactory that this bean generates for accessing a JDBC connection to perform * the script. * * @throws DataAccessException in case of script execution errors * @see org.hibernate.cfg.Configuration#generateSchemaCreationScript * @see org.hibernate.tool.hbm2ddl.SchemaExport#create */ public void createDatabaseSchema() throws DataAccessException { logger.info("Creating database schema for Hibernate SessionFactory"); DataSource dataSource = getDataSource(); if (dataSource != null) { // Make given DataSource available for the schema update. configTimeDataSourceHolder.set(dataSource); } try { SessionFactory sessionFactory = getSessionFactory(); final Dialect dialect = ((SessionFactoryImplementor) sessionFactory).getDialect(); HibernateTemplate hibernateTemplate = new HibernateTemplate(sessionFactory); hibernateTemplate.execute( new HibernateCallback<Object>() { @Override public Object doInHibernate(Session session) throws HibernateException, SQLException { Connection con = session.connection(); String[] sql = getConfiguration().generateSchemaCreationScript(dialect); executeSchemaScript(con, sql); return null; } }); } finally { if (dataSource != null) { configTimeDataSourceHolder.remove(); } } }
public static void commitTransaction() throws Exception { if (tranConnection.get() == null) { throw new Exception("Can't commit: this thread isn't currently in a " + "transaction"); } tranConnection.get().commit(); tranConnection.set(null); }
/** @see LoopIterationListener#iterationStart(LoopIterationEvent) */ @Override public void iterationStart(LoopIterationEvent event) { // Cannot use getThreadContext() as not cloned per thread JMeterVariables variables = JMeterContextService.getContext().getVariables(); long start = getStart(); long end = getEnd(); long increment = getIncrement(); if (!isPerUser()) { synchronized (this) { if (globalCounter == Long.MIN_VALUE || globalCounter > end) { globalCounter = start; } variables.put(getVarName(), formatNumber(globalCounter)); globalCounter += increment; } } else { long current = perTheadNumber.get().longValue(); if (isResetOnThreadGroupIteration()) { int iteration = variables.getIteration(); Long lastIterationNumber = perTheadLastIterationNumber.get(); if (iteration != lastIterationNumber.longValue()) { // reset current = getStart(); } perTheadLastIterationNumber.set(Long.valueOf(iteration)); } variables.put(getVarName(), formatNumber(current)); current += increment; if (current > end) { current = start; } perTheadNumber.set(Long.valueOf(current)); } }