List of usage examples for java.lang Thread yield
public static native void yield();
From source file:org.rzo.yajsw.os.ms.win.w32.WindowsXPProcess.java
/** * Kill.// w ww.ja v a 2 s.c o m * * @param pid * the pid * @param code * the code * * @return true, if successful */ public static boolean kill(int pid, int code) { if (pid <= 0) return false; Pointer hProcess = MyKernel32.INSTANCE.OpenProcess(MyKernel32.PROCESS_TERMINATE, false, pid); boolean result = MyKernel32.INSTANCE.TerminateProcess(hProcess, code); Thread.yield(); if (!result) System.out.println("kill failed: " + pid); MyKernel32.INSTANCE.CloseHandle(hProcess); return result; }
From source file:com.gemstone.gemfire.internal.cache.OplogJUnitTest.java
/** * This is used to test bug 35012 where a remove operation on a key gets * unrecorded due to switching of Oplog if it happens just after the remove * operation has destroyed the in memory entry & is about to acquire the * readlock in DiskRegion to record the same. If the Oplog has switched during * that duration , the bug would appear// w ww .j a va 2 s . co m * * @author Asif */ @Test public void testBug35012() { final int MAX_OPLOG_SIZE = 500; diskProps.setMaxOplogSize(MAX_OPLOG_SIZE); diskProps.setPersistBackup(true); diskProps.setRolling(false); diskProps.setSynchronous(true); diskProps.setOverflow(false); final byte[] val = new byte[200]; try { region = DiskRegionHelperFactory.getSyncPersistOnlyRegion(cache, diskProps, Scope.LOCAL); region.put("key1", val); region.put("key2", val); region.put("key3", val); final Thread th = new Thread(new Runnable() { public void run() { region.remove("key1"); } }); // main thread acquires the write lock ((LocalRegion) region).getDiskRegion().acquireWriteLock(); try { th.start(); Thread.yield(); DiskRegion dr = ((LocalRegion) region).getDiskRegion(); dr.testHook_getChild().forceRolling(dr); } finally { ((LocalRegion) region).getDiskRegion().releaseWriteLock(); } DistributedTestCase.join(th, 30 * 1000, null); region.close(); region = DiskRegionHelperFactory.getSyncPersistOnlyRegion(cache, diskProps, Scope.LOCAL); assertEquals(region.size(), 2); } catch (Exception e) { this.logWriter.error("Exception occurred ", e); fail("The test could not be completed because of exception .Exception=" + e); } closeDown(); }
From source file:org.apache.geode.internal.cache.partitioned.PersistentColocatedPartitionedRegionDUnitTest.java
/** * Test what happens when we restart persistent members while there is an accessor concurrently * performing puts. This is for bug 43899 *///from ww w . j a va 2 s.c om @Test public void testRecoverySystemWithConcurrentPutter() throws Throwable { Host host = Host.getHost(0); VM vm0 = host.getVM(0); VM vm1 = host.getVM(1); VM vm2 = host.getVM(2); VM vm3 = host.getVM(3); // Define all of the runnables used in this test // runnable to create accessors SerializableRunnable createAccessor = new SerializableRunnable("createAccessor") { public void run() { Cache cache = getCache(); AttributesFactory af = new AttributesFactory(); PartitionAttributesFactory paf = new PartitionAttributesFactory(); paf.setRedundantCopies(1); paf.setLocalMaxMemory(0); af.setPartitionAttributes(paf.create()); af.setDataPolicy(DataPolicy.PARTITION); cache.createRegion(PR_REGION_NAME, af.create()); paf.setColocatedWith(PR_REGION_NAME); af.setPartitionAttributes(paf.create()); cache.createRegion("region2", af.create()); } }; // runnable to create PRs SerializableRunnable createPRs = new SerializableRunnable("createPRs") { public void run() { Cache cache = getCache(); DiskStore ds = cache.findDiskStore("disk"); if (ds == null) { ds = cache.createDiskStoreFactory().setDiskDirs(getDiskDirs()).create("disk"); } AttributesFactory af = new AttributesFactory(); PartitionAttributesFactory paf = new PartitionAttributesFactory(); paf.setRedundantCopies(1); af.setPartitionAttributes(paf.create()); af.setDataPolicy(DataPolicy.PERSISTENT_PARTITION); af.setDiskStoreName("disk"); cache.createRegion(PR_REGION_NAME, af.create()); paf.setColocatedWith(PR_REGION_NAME); af.setPartitionAttributes(paf.create()); cache.createRegion("region2", af.create()); } }; // runnable to close the cache. SerializableRunnable closeCache = new SerializableRunnable("closeCache") { public void run() { closeCache(); } }; // Runnable to do a bunch of puts handle exceptions // due to the fact that member is offline. SerializableRunnable doABunchOfPuts = new SerializableRunnable("doABunchOfPuts") { public void run() { Cache cache = getCache(); Region region = cache.getRegion(PR_REGION_NAME); try { for (int i = 0;; i++) { try { region.get(i % NUM_BUCKETS); } catch (PartitionOfflineException expected) { // do nothing. } catch (PartitionedRegionStorageException expected) { // do nothing. } Thread.yield(); } } catch (CacheClosedException expected) { // ok, we're done. } } }; // Runnable to clean up disk dirs on a members SerializableRunnable cleanDiskDirs = new SerializableRunnable("Clean disk dirs") { public void run() { try { cleanDiskDirs(); } catch (IOException e) { throw new RuntimeException(e); } } }; // Create the PR two members vm1.invoke(createPRs); vm2.invoke(createPRs); // create the accessor. vm0.invoke(createAccessor); // Create some buckets. createData(vm0, 0, NUM_BUCKETS, "a"); createData(vm0, 0, NUM_BUCKETS, "a", "region2"); // backup the system. We use this to get a snapshot of vm1 and vm2 // when they both are online. Recovering from this backup simulates // a simulataneous kill and recovery. backup(vm3); // close vm1 and vm2. vm1.invoke(closeCache); vm2.invoke(closeCache); // restore the backup vm1.invoke(cleanDiskDirs); vm2.invoke(cleanDiskDirs); restoreBackup(2); // in vm0, start doing a bunch of concurrent puts. AsyncInvocation async0 = vm0.invokeAsync(doABunchOfPuts); // This recovery should not hang (that's what we're testing for // here. AsyncInvocation async1 = vm1.invokeAsync(createPRs); AsyncInvocation async2 = vm2.invokeAsync(createPRs); async1.getResult(MAX_WAIT); async2.getResult(MAX_WAIT); // close the cache in vm0 to stop the async puts. vm0.invoke(closeCache); // make sure we didn't get an exception async0.getResult(MAX_WAIT); }
From source file:stg.pr.engine.CProcessRequestEngine.java
/** * Empties the Connection pool and closes the engine log file *///from w ww . j a v a2s . c om private void closeAll() { objEngineLogger_.log(LogLevel.NOTICE, "Initiating Clean Shutdown"); if (lStuckThreadMonitorInterval_ > 0) { objEngineLogger_.log(LogLevel.NOTICE, "Stopping Monitor Thread"); if (tMonitorThread_.isAlive()) { tMonitorThread_.interrupt(); } else { objEngineLogger_.log(LogLevel.NOTICE, "Monitor Thread already stopped."); } } while (!(vectorThreads_.isEmpty() && vectorThreadsGroup_.isEmpty())) // bGroupedEngineTerminationConfirmed_)) { objEngineLogger_.log(LogLevel.NOTICE, "Waiting while the Current processes are finished...."); if (objEngineLogger_.isInfoEnabled()) { objEngineLogger_.info("Total Standalone Processes running " + vectorThreads_.size()); objEngineLogger_.info("Total Grouped Processes running " + vectorThreadsGroup_.size()); objEngineLogger_.info("Shutdown Hook Sleeping for 10 minutes..."); } try { if (tInterrupt_ != null) { Thread.yield(); TimeUnit.MINUTES.sleep(10); // Thread.sleep(600000l); // The following two lines are commented as suggested by // Eclipse editor. Instead of these // two lines the above two lines are used. We should get the // same results....Kedar..23/09/2003 // tInterrupt_.yield(); // tInterrupt_.sleep(600000l); } } catch (InterruptedException ie) { // dummy exception. do nothing. The Running process will // interrupt this thread. } } if (tMonitorThread_ != null) { tMonitorThread_.interrupt(); while (tMonitorThread_.isAlive()) { } } // if (objEngineLogger_.isInfoEnabled()) { // objEngineLogger_.info("Closing PreparedStatements ..."); // } // if (objPrCont_ != null) { // objPrCont_.close(); // } try { if (dataSourceFactory_ != null) { try { if (staticConnection_ != null) { staticConnection_.close(); } } catch (SQLException e) { // No need to throw exception. } if (objEngineLogger_.isInfoEnabled()) { objEngineLogger_.info("Emptying Data Sources ...."); } if (dataSourceFactory_.shutdown()) { objEngineLogger_.info("All Data Source emptied successfully."); } } } catch (Exception e) { objEngineLogger_.error(e); // No need to throw exception. PRE is closing down. } // if (objEngineLogger_ != null) { // objEngineLogger_.info("Closing System Log ...."); // objEngineLogger_.close(); // } // if (httpserver_.isStarted()) // { // if (objEngineLogger_.isInfoEnabled()) { // objEngineLogger_.info("Stoping Web Service"); // } // httpserver_.stop(); // } stopWebServer(); if (!Thread.currentThread().getName().equals("shutdown")) { if (Hazelcast.getCluster().getMembers().size() == 1) { printPossibleMemoryLeaks(); } } Iterator<Service> iter = services_.values().iterator(); while (iter.hasNext()) { Service instance = iter.next(); instance.destroy(context_); iter.remove(); } // if (reportService != null) { // reportService.shutdown(); // if (objEngineLogger_.isInfoEnabled()) { // objEngineLogger_ // .info("Waiting for the current reports, if any, to finish."); // } // while (!reportService.isTerminated()) { // try { // TimeUnit.SECONDS.sleep(20); // } catch (InterruptedException e) { // e.printStackTrace(); // } // if (objEngineLogger_.isInfoEnabled()) { // objEngineLogger_.info("Waiting for Active(" // + reportService.getCurrentActiveCount() // + ") and Pending(" // + reportService.getCurrentPendingQueueSize() // + ") reports to be completed."); // } // } // } if (objEngineLogger_.isInfoEnabled()) { objEngineLogger_.info("Engine Termination Confirmed...."); } // bEngineTerminationConfirmed_ = true; }
From source file:de.innovationgate.webgate.api.WGDatabase.java
/** * Processes a list of updates, that occured in the background. Caches will * be maintained and events will be fired. * //from w ww.j a va2s . c o m * @param updatedDocuments * List of WGUpdateLog objects, representing database updates * @throws WGAPIException */ private void processChanges(List<WGUpdateLog> updatedDocuments) throws WGAPIException { if (!isSessionOpen()) { throw new WGClosedSessionException(); } verboseCacheManagement("Performing incremental cache update"); if (getSessionContext().isTransactionActive() || !hasFeature(FEATURE_FIND_UPDATED_DOCS)) { return; } if (updatedDocuments == null) { WGFactory.getLogger().error("No updated documents provided for change processing"); return; } // Iterate through update events Iterator<WGUpdateLog> changes = updatedDocuments.iterator(); while (changes.hasNext()) { Thread.yield(); WGUpdateLog log = changes.next(); verboseCacheManagement("Processing change log " + log.getRevision().getRevisionValue().toString() + ", Type " + log.getType() + ", Target " + log.getDocumentKey() + ", Transactional: " + getSessionContext().isTransactionActive()); // Call backend change listeners for (WGBackendChangeListener listener : this.backendChangeListeners) { listener.processChange(this, log); } // Filter out rows that do not refer to document updates (like ACL // entries) if (log.getDocumentKey().startsWith("$")) { verboseCacheManagement("Non-document change log. Skipped"); continue; } WGDocumentKey docKey = new WGDocumentKey(log.getDocumentKey()); // Perform all neccessary operation for the given type of update if (log.getType() == WGUpdateLog.TYPE_UPDATE) { try { clearNonexistentDocIndicatorForDocument(log.getDocumentKey()); WGDocument doc = getDocumentByKey(log.getDocumentKey()); if (doc != null) { WGDatabaseRevision cacheRevision = doc.getCacheRevision(); if (cacheRevision != null && log.getRevision() != null && cacheRevision.isUniqueValue() && cacheRevision.compareTo(log.getRevision()) >= 0) { verboseCacheManagement("Document already on cache revision. Skipped"); continue; } } verboseCacheManagement("Performing creation/update of doc " + log.getDocumentKey()); documentSaved(doc, docKey, true, false, log.getRevision()); // If metadata module was updated in background we drop the complete cache // as it might symbolize the end of a batch update process (F00004402) if (log.getDocumentKey().startsWith(WGCSSJSModule.METADATA_MODULE_QUALIFIER)) { verboseCacheManagement( "Update of metadata module " + log.getDocumentKey() + ". Complete cache refresh"); refresh(); } } catch (WGDeletedException e) { // Silently ignore here. Most likely this update log refers a backend entity that has already been deleted in the meantime. // Continue processing to pickup deletion log (#00002163) } } else if (log.getType() == WGUpdateLog.TYPE_DELETE) { try { WGDocument doc = getDocumentByDocumentKeyFromCache(docKey, false); if (doc != null) { WGDatabaseRevision cacheRevision = doc.getCacheRevision(); if (cacheRevision != null && log.getRevision() != null && cacheRevision.isUniqueValue() && cacheRevision.compareTo(log.getRevision()) >= 0) { verboseCacheManagement("Document already on cache revision. Skipped"); continue; } } verboseCacheManagement("Performing deletion of doc " + log.getDocumentKey()); documentRemoved(doc, docKey, false, (docKey.getDocType() == WGDocument.TYPE_CONTENT), log.getRevision()); } catch (WGDocumentDoesNotExistException e) { // NOOP: Was deleted and already marked as nonexistent } } else if (log.getType() == WGUpdateLog.TYPE_STRUCTMOVE) { try { WGStructEntry struct = (WGStructEntry) getDocumentByKey(log.getDocumentKey()); if (struct != null) { verboseCacheManagement("Performing struct movage of doc " + log.getDocumentKey()); processMovedDocuments(struct, false); } } catch (WGDeletedException e) { // Silently ignore here. Most likely this update log refers a backend entity that has already been deleted in the meantime. // Continue processing to pickup deletion log (#00002163) } } else { WGFactory.getLogger().warn("Unknown log type: " + log.getType()); } getSessionContext().clearCache(); } // Throw global update event so event listeners may update this.fireDatabaseEvent(new WGDatabaseEvent(this, WGDatabaseEvent.TYPE_UPDATE)); }
From source file:org.quickserver.net.server.QuickServer.java
/** * Starts server in non-blocking mode./*from w w w .j a v a 2 s. c o m*/ * @since 1.4.5 */ private void runNonBlocking(TheClient theClient) throws Exception { int selectCount = 0; Iterator iterator = null; SelectionKey key = null; ServerSocketChannel serverChannel = null; SocketChannel socketChannel = null; Socket client = null; ClientHandler _chPolled = null; boolean stopServerProcessed = false; int linger = getBasicConfig().getAdvancedSettings().getSocketLinger(); registerChannelRequestMap = new HashMap(); int socketTrafficClass = 0; if (getBasicConfig().getAdvancedSettings().getClientSocketTrafficClass() != null) { socketTrafficClass = Integer .parseInt(getBasicConfig().getAdvancedSettings().getClientSocketTrafficClass()); } while (true) { selectCount = selector.select(500); //selectCount = selector.select();//for testing //check for any pending registerChannel req. synchronized (registerChannelRequestMap) { if (registerChannelRequestMap.size() > 0) { RegisterChannelRequest req = null; Object hashkey = null; iterator = registerChannelRequestMap.keySet().iterator(); while (iterator.hasNext()) { hashkey = iterator.next(); req = (RegisterChannelRequest) registerChannelRequestMap.get(hashkey); req.register(getSelector()); } iterator = null; registerChannelRequestMap.clear(); } //if } //sync if (stopServer == true && stopServerProcessed == false) { logger.warning("Closing " + getName()); serverSocketChannel.close(); stopServerProcessed = true; server = null; serverSocketChannel = null; setServiceState(Service.STOPPED); logger.warning("Closed " + getName()); processServerHooks(ServerHook.POST_SHUTDOWN); } if (stopServer == false && stopServerProcessed == true) { logger.finest("Server must have re-started.. will break"); break; } if (selectCount == 0 && stopServerProcessed == true) { java.util.Set keyset = selector.keys(); if (keyset.isEmpty() == true && getClientCount() <= 0) { break; } else { continue; } } else if (selectCount == 0) { continue; } iterator = selector.selectedKeys().iterator(); while (iterator.hasNext()) { key = (SelectionKey) iterator.next(); if (key.isValid() == false) { iterator.remove(); continue; } if (key.isAcceptable() && stopServer == false) { logger.finest("Key is Acceptable"); serverChannel = (ServerSocketChannel) key.channel(); socketChannel = serverChannel.accept(); if (socketChannel == null) { iterator.remove(); continue; } client = socketChannel.socket(); if (linger < 0) { client.setSoLinger(false, 0); } else { client.setSoLinger(true, linger); } client.setTcpNoDelay(getBasicConfig().getAdvancedSettings().getClientSocketTcpNoDelay()); if (getBasicConfig().getAdvancedSettings().getClientSocketTrafficClass() != null) { client.setTrafficClass(socketTrafficClass);//low delay=10 } //logger.fine("ReceiveBufferSize: "+client.getReceiveBufferSize()); if (getBasicConfig().getAdvancedSettings().getClientSocketSendBufferSize() != 0) { client.setSendBufferSize( getBasicConfig().getAdvancedSettings().getClientSocketSendBufferSize()); //logger.fine("SendBufferSize: "+client.getSendBufferSize()); } if (checkAccessConstraint(client) == false) { iterator.remove(); continue; } socketChannel.configureBlocking(false); theClient.setTrusted(getSkipValidation()); theClient.setSocket(socketChannel.socket()); theClient.setSocketChannel(socketChannel); if (clientDataClass != null) { if (getClientDataPool() == null) { clientData = (ClientData) clientDataClass.newInstance(); } else { //borrow a object from pool clientData = (ClientData) getClientDataPool().borrowObject(); } theClient.setClientData(clientData); } //Check if max connection has reached if (getSkipValidation() != true && maxConnection != -1 && getClientHandlerPool().getNumActive() >= maxConnection) { theClient.setClientEvent(ClientEvent.MAX_CON); } else { theClient.setClientEvent(ClientEvent.ACCEPT); } try { _chPolled = (ClientHandler) getClientHandlerPool().borrowObject(); logger.finest("Asking " + _chPolled.getName() + " to handle."); _chPolled.handleClient(theClient); } catch (java.util.NoSuchElementException nsee) { logger.warning("Could not borrow ClientHandler Object from pool. Error: " + nsee); logger.warning("Closing SocketChannel [" + serverChannel.socket() + "] since no ClientHandler available."); socketChannel.close(); } if (_chPolled != null) { try { getClientPool().addClient(_chPolled, true); } catch (java.util.NoSuchElementException nsee) { logger.warning("Could not borrow Thread from pool. Error: " + nsee); //logger.warning("Closing SocketChannel ["+serverChannel.socket()+"] since no Thread available."); //socketChannel.close(); //returnClientHandlerToPool(_chPolled); } _chPolled = null; } socketChannel = null; client = null; setSkipValidation(false);//reset it back } else if (key.isValid() && key.isReadable()) { boolean addedEvent = false; ClientHandler _ch = null; try { _ch = (ClientHandler) key.attachment(); logger.finest("Key is Readable, removing OP_READ from interestOps for " + _ch.getName()); key.interestOps(key.interestOps() & (~SelectionKey.OP_READ)); _ch.addEvent(ClientEvent.READ); addedEvent = true; //_ch.setSelectionKey(key); getClientPool().addClient(_ch); } catch (CancelledKeyException cke) { logger.fine("Ignored Error - Key was Cancelled: " + cke); } catch (java.util.NoSuchElementException nsee) { logger.finest("NoSuchElementException: " + nsee); if (addedEvent) _ch.removeEvent(ClientEvent.READ); continue;//no need to remove the key } _ch = null; } else if (key.isValid() && key.isWritable()) { if (getClientPool().shouldNioWriteHappen() == false) { continue; //no need to remove the key } boolean addedEvent = false; ClientHandler _ch = null; try { _ch = (ClientHandler) key.attachment(); logger.finest("Key is Writable, removing OP_WRITE from interestOps for " + _ch.getName()); //remove OP_WRITE from interest set key.interestOps(key.interestOps() & (~SelectionKey.OP_WRITE)); _ch.addEvent(ClientEvent.WRITE); addedEvent = true; //_ch.setSelectionKey(key); getClientPool().addClient(_ch); } catch (CancelledKeyException cke) { logger.fine("Ignored Error - Key was Cancelled: " + cke); } catch (java.util.NoSuchElementException nsee) { logger.finest("NoSuchElementException: " + nsee); if (addedEvent) _ch.removeEvent(ClientEvent.WRITE); continue;//no need to remove the key } _ch = null; } else if (stopServer == true && key.isAcceptable()) { //we will not accept this key setSkipValidation(false);//reset it back } else { logger.warning("Unknown key got in SelectionKey: " + key); } iterator.remove(); //Remove key Thread.yield(); } //end of iterator iterator = null; } //end of loop }
From source file:com.kodemore.utility.Kmu.java
/** * A convenience method for consistency with other thread methods that are * wrapped here. */ public static void yield() { Thread.yield(); }
From source file:stg.pr.engine.CProcessRequestEngine.java
/** * Starts the service engine for the Grouped Requests. Gets the connection * from the pool and Continuously scans the PROCESS_REQUEST table for queued * grouped requests and executes them sequentially * //w w w . j a v a2 s . c o m * <p> * Scanning continues in a loop until the tEngine_ thread is interrupted. * </p> * <p> * The query picks up requests, from the table PROCESS_REQUEST, that have * the Req_Stat='Q' and GRP_ST_IND = 'G'. If requests are found then each * record is processed sequentially depending on the sequence given in the * group. If no records are found then the engine waits for a specified time * (picked up from property file) and then resumes scanning * </p> * */ private void startGroupServiceEngine() { if (objEngineLogger_.isInfoEnabled()) { objEngineLogger_.info("Starting Group Service Engine..."); } Connection conForGroupedRequest = null; PreparedStatement psm = null; PreparedStatement psmu = null; try { objEngineLogger_.log(Level.INFO, "Waiting for the cluster handshake."); while (!bClusterHandShakeDone_) { // wait do nothing. if (bEngineTerminated_.get() || bGroupedEngineTerminated_.get()) { tEngine_.interrupt(); break; // break the while loop. } } if (!(bEngineTerminated_.get() || bGroupedEngineTerminated_.get())) { if (objEngineLogger_.isDebugEnabled()) { objEngineLogger_.debug("Getting Connection from the pool ...."); } // conForGroupedRequest = // poolManager_.getConnection(CSettings.get("pr.dsforgroupeng")); conForGroupedRequest = dataSourceFactory_.getDataSource(CSettings.get("pr.dsforgroupeng")) .getConnection(); psmu = conForGroupedRequest.prepareStatement( "UPDATE process_request SET req_stat = ? WHERE grp_id = ? AND req_stat = ?"); psm = conForGroupedRequest.prepareStatement( "Select distinct grp_id from process_request where grp_st_ind = ? and req_stat = ? and scheduled_time <= ?"); objEngineLogger_.log(LogLevel.NOTICE, "Group Service Engine Started...."); } while (!tEngine_.isInterrupted()) { boolean bTerminate = false; // try { // LicenseVerifier.verify(readLicense()); // } catch (LicenseContentException lce) { // bTerminate = true; // objEngineLogger_.fatal(lce.getLocalizedMessage()); // } catch (Exception e) { // bTerminate = true; // objEngineLogger_.fatal(e.getLocalizedMessage()); // } if (bTerminate) { if (tEngine_ != null) { tEngine_.interrupt(); } break; } ResultSet rs = null; try { boolean bDoesRequestExists = false; if (!bGroupedEngineTerminated_.get()) { psm.clearParameters(); psm.setString(1, "G"); psm.setString(2, REQUEST_STATUS.QUEUED.getID()); psm.setTimestamp(3, getCurrentTimestamp(conForGroupedRequest)); rs = psm.executeQuery(); while (rs.next() && !tEngine_.isInterrupted()) { if (iGrpThreadCounter_.get() <= iGroupMaximumThread_) { long lGroupId = rs.getLong(1); bDoesRequestExists = true; try { if (objEngineLogger_.isInfoEnabled()) { objEngineLogger_.info("Begin Group Transaction ..."); } conForGroupedRequest.setAutoCommit(false); if (objEngineLogger_.isDebugEnabled()) { objEngineLogger_.debug( "Update Status to... " + REQUEST_STATUS.LAUNCHING.getDescription()); } psmu.setString(1, REQUEST_STATUS.LAUNCHING.getID()); psmu.setLong(2, lGroupId); psmu.setString(3, REQUEST_STATUS.QUEUED.getID()); psmu.executeUpdate(); if (objEngineLogger_.isDebugEnabled()) { objEngineLogger_.debug("Commit Transaction ..."); } conForGroupedRequest.commit(); // } catch (Exception e) { try { objEngineLogger_.error("Rollback Transaction ...", e); conForGroupedRequest.rollback(); } catch (Exception ex) { throw ex; } throw e; } finally { try { conForGroupedRequest.setAutoCommit(true); } catch (Exception ex) { if (objEngineLogger_.isEnabledFor(Level.WARN)) { objEngineLogger_.warn("Dummy Exception and can be ignored.", ex); } } } CGroupedThreadProcess cgtp = new CGroupedThreadProcess("Thread-Grp#" + lGroupId); cgtp.setGroupId(lGroupId); addGroupProcess(cgtp); cgtp.start(); // startServiceForGroupedRequests(conForGroupedRequest, // rs.getLong(1)); } if (objEngineLogger_.isEnabledFor(LogLevel.FINE)) { objEngineLogger_.log(LogLevel.FINE, "Group Engine: Maximum thread spawning capacity (#" + (iGrpThreadCounter_.get() - 1) + ") has reached. Going into Wait mode till one of the JOB gets over."); } long lCurrentTime = System.currentTimeMillis(); while (iGrpThreadCounter_.get() > iGroupMaximumThread_) { // try // { // Thread.sleep(10000); // } // catch (InterruptedException ie) // { // System.exit(1); // } } long lWaitTime = System.currentTimeMillis() - lCurrentTime; if (objEngineLogger_.isEnabledFor(LogLevel.FINE)) { objEngineLogger_.log(LogLevel.FINE, "Group Engine :Wait Over. Waited for #" + lWaitTime + " milliseconds for some JOB to get over."); } } } // If group engine is not terminated. if (!bDoesRequestExists) { lWaitInterval_ = (Math.abs(Long.parseLong(CSettings.get("pr.waitinterval")))); if (objEngineLogger_.isInfoEnabled()) { objEngineLogger_.info( mfSleepMessageForEngine_.format(new Object[] { "Group", lWaitInterval_ })); } try { Thread.yield(); TimeUnit.SECONDS.sleep(lWaitInterval_); // Thread.sleep(lWaitInterval_); } catch (InterruptedException ie) { // This is not an exception. objEngineLogger_.log(LogLevel.NOTICE, "Grouped Engine Thread Interrupted .."); break; } } // end of else } catch (IOException ioe) { // This is under the assumption that the IO Exception can // never be thrown by the object // executed by the Engine as it can only throw // CProcessRequestEngineException. This exception // means that something wrong has happened in the // Connection. try { closeSQLStatement(psmu); closeSQLStatement(psm); conForGroupedRequest = refreshJDBCConnection(4, conForGroupedRequest, CSettings.get("pr.dsforgroupeng")); // Connection gets refereshed but not the statements. // Therefore the statemetns are refreshed/recreated // here. psmu = conForGroupedRequest.prepareStatement( "UPDATE process_request SET req_stat = ? WHERE grp_id = ? AND req_stat = ?"); psm = conForGroupedRequest.prepareStatement( "Select distinct grp_id from process_request where grp_st_ind = ? and req_stat = ? and scheduled_time <= ?"); } catch (Exception e) { stopMessageForEmail_ = exceptionToString(ioe); objEngineLogger_.fatal( "Grouped Request: IOException Caught. Terminating GroupedRequest Engine", ioe); setReboot(true); break; } } catch (SQLException se) { // This is under the assumption that the SQL Exception can // never be thrown by the object // executed by the Engine as it can only throw // CProcessRequestEngineException. This exception // means that something wrong has happened in the Engine // itself and so engine should get terminated. try { closeSQLStatement(psmu); closeSQLStatement(psm); conForGroupedRequest = refreshJDBCConnection(4, conForGroupedRequest, CSettings.get("pr.dsforgroupeng")); // Connection gets refereshed but not the statements. // Therefore the statemetns are refreshed/recreated // here. psmu = conForGroupedRequest.prepareStatement( "UPDATE process_request SET req_stat = ? WHERE grp_id = ? AND req_stat = ?"); psm = conForGroupedRequest.prepareStatement( "Select distinct grp_id from process_request where grp_st_ind = ? and req_stat = ? and scheduled_time <= ?"); } catch (Exception e) { stopMessageForEmail_ = exceptionToString(se); objEngineLogger_.fatal( "Grouped Request: SQLException Caught. Terminating GroupedRequest Engine", se); setReboot(true); break; } } catch (RuntimeException ree) { objEngineLogger_.error("Grouped Request: Runtime Exception Caught", ree); // no need to throw exception. Just catch. } catch (Exception e) { objEngineLogger_.error("Grouped Request: Exception Caught", e); // no need to throw exception. Just catch. } finally { if (rs != null) { rs.close(); } } } // end of while } catch (Exception e) { objEngineLogger_.fatal("Grouped Request Main: Exception Caught", e); // no need to throw exception. Just catch. } finally { closeSQLStatement(psmu); closeSQLStatement(psm); try { if (conForGroupedRequest != null) { if (objEngineLogger_.isInfoEnabled()) { objEngineLogger_.info("Releasing Grouped Connection to the pool ...."); } conForGroupedRequest.close(); } } catch (SQLException e) { // do nothing } // objEngineLogger_.log(LogLevel.NOTICE, // "Grouped Request Engine Stopped .."); if (objEngineLogger_.isDebugEnabled()) { objEngineLogger_.debug("Interrupting Shutdown Hook from Grouped Requests..."); } // try { // poolManager_.emptyPool(CSettings.get("pr.dsforgroupeng")); // } catch (SQLException e) { // //do nothing // } if (tInterrupt_ != null) { if (tInterrupt_.isAlive()) { tInterrupt_.interrupt(); } else { if (tMain_.isAlive()) { tMain_.interrupt(); } } } else { if (tMain_.isAlive()) { tMain_.interrupt(); } } } }
From source file:stg.pr.engine.CProcessRequestEngine.java
/** * Refreshes the JDBC connection./*from w w w . ja va 2 s.co m*/ * * The method will check the passed connection if it is active. If found * active it will throw an exception. This method should be called only when * an IO or SQLException is received. The method expects that the passed * connection is not active. * * The method then returns the connection to the pool and tries to get a new * connection from the pool identified by the parameter * <code>pstrPoolIdentifier</code>. This is done for <code>iTries</code>. * Even after the said tires if the JDBC connection is not refreshed then * the method throws an exception. * * @param iTries * Number of tries the method should do the refresh. * @param pcon * Inactive JDBC Connection. * @param pstrPoolIdentifier * Pool Identifier. * @return Connection * @throws Exception */ private Connection refreshJDBCConnection(int iTries, Connection pcon, String pstrPoolIdentifier) throws Exception { try { // if (pcon instanceof jdbc.tuning.ConnectionWrapper) { // ConnectionWrapper wrapper = (ConnectionWrapper) pcon; // if (wrapper.isActive()) { // throw new // CProcessRequestEngineException("Connection is active."); // } // } pcon.close(); } catch (SQLException sqle) { // dummy catch. } Exception exception = null; Connection con = null; for (int i = 0; i < iTries; i++) { if (objEngineLogger_.isInfoEnabled()) { objEngineLogger_ .info("Waiting for #" + lWaitInterval_ + " Seconds before refreshing the JDBC Connection"); } try { Thread.yield(); TimeUnit.SECONDS.sleep(lWaitInterval_); // Thread.sleep(lWaitInterval_); } catch (InterruptedException ie) { // do nothing } exception = null; if (objEngineLogger_.isDebugEnabled()) { objEngineLogger_.debug("Refreshing JDBCConnection. Try #" + (i + 1) + " of #" + iTries); } // it is expected to get exceptions. try { // con = poolManager_.getConnection(pstrPoolIdentifier); con = dataSourceFactory_.getDataSource(pstrPoolIdentifier).getConnection(); if (objEngineLogger_.isDebugEnabled()) { objEngineLogger_.debug("JDBCConnection refreshed...Restarting the infinite loop."); } } catch (SQLException sqle) { exception = sqle; } catch (IOException ioe) { exception = ioe; } catch (Exception e) { exception = e; } if (con != null) return con; if (objEngineLogger_.isDebugEnabled()) { objEngineLogger_.debug("Unable to refresh JDBCConnection even after attempt #" + (i + 1)); } } throw exception; }