private void doShutdown(boolean force) { long start = Clock.currentTimeMillis(); logger.finest("** we are being asked to shutdown when active = " + String.valueOf(active)); if (!force && isActive()) { final int maxWaitSeconds = groupProperties.GRACEFUL_SHUTDOWN_MAX_WAIT.getInteger(); if (!partitionService.prepareToSafeShutdown(maxWaitSeconds, TimeUnit.SECONDS)) { logger.warning( "Graceful shutdown could not be completed in " + maxWaitSeconds + " seconds!"); } } if (isActive()) { if (!force) { clusterService.sendShutdownMessage(); } // set the joined=false first so that // threads do not process unnecessary // events, such as remove address joined.set(false); setActive(false); setMasterAddress(null); try { Runtime.getRuntime().removeShutdownHook(shutdownHookThread); } catch (Throwable ignored) { } if (managementCenterService != null) { managementCenterService.shutdown(); } logger.finest("Shutting down client command service"); clientEngine.shutdown(); logger.finest("Shutting down node engine"); nodeEngine.shutdown(); if (multicastService != null) { logger.finest("Shutting down multicast service"); multicastService.stop(); } logger.finest("Shutting down connection manager"); connectionManager.shutdown(); textCommandService.stop(); masterAddress = null; if (securityContext != null) { securityContext.destroy(); } initializer.destroy(); serializationService.destroy(); int numThreads = threadGroup.activeCount(); Thread[] threads = new Thread[numThreads * 2]; numThreads = threadGroup.enumerate(threads, false); for (int i = 0; i < numThreads; i++) { Thread thread = threads[i]; if (thread.isAlive()) { logger.finest("Shutting down thread " + thread.getName()); thread.interrupt(); } } failedConnections.clear(); systemLogService.shutdown(); logger.info( "Hazelcast Shutdown is completed in " + (Clock.currentTimeMillis() - start) + " ms."); } }
@Test public void testGetSize() throws Exception { String Id1 = "1"; String Id2 = "2"; Clock cl = new Clock(Id1); // create clock with id equals 1 Assert.assertEquals(1, cl.getSize()); }
// After a little while, if nothing has gone wrong, if we are next to a pastr and no one // else is building or has built a noise tower, build one. private boolean tryBuildNoiseTower() throws GameActionException { if (!rc.isActive()) return false; if (Clock.getRoundNum() < 200) return false; if (rc.senseRobotCount() < 6) return false; // A problem with building a noise tower is that it makes us more vulnerable to // a rush. If it's early and the opponent hasn't build a pastr, let's hold off // in case it means that they are rushing. if (Clock.getRoundNum() < 300 && rc.sensePastrLocations(them).length == 0) return false; // Only allowed to build noise tower if adjacent to pastr MapLocation[] ourPastrs = rc.sensePastrLocations(us); if (ourPastrs.length == 0 || !here.isAdjacentTo(ourPastrs[0])) return false; // Check if someone else is already building a noise tower MapLocation existingBuilder = MessageBoard.BUILDING_NOISE_TOWER.readMapLocation(); if (existingBuilder != null) { if (rc.senseNearbyGameObjects(Robot.class, existingBuilder, 1, us).length > 0) { return false; } } // Construct the noise tower and advertise the fact that we are doing it MessageBoard.BUILDING_NOISE_TOWER.writeMapLocation(here); constructNoiseTower(ourPastrs[0]); return true; }
public static boolean doWeNeedGenerator() throws GameActionException { if (rc.readBroadcast(Constants.campChannel) == Constants.campGenInProduction) return false; if (Clock.getRoundNum() - allInRound < 80) return false; if (rc.readBroadcast(Constants.commandChannel) == Constants.commandRally && rc.getTeamPower() > powerThreshold) return false; if (rc.getTeamPower() < minPowerThreshold && Clock.getRoundNum() > minRoundThreshold) { return true; } gencount = 0; soldiercount = 0; othercount = 0; Robot[] robos = rc.senseNearbyGameObjects(Robot.class, new MapLocation(0, 0), 1000000, rc.getTeam()); for (Robot r : robos) { RobotType rt = rc.senseRobotInfo(r).type; if (rt == RobotType.GENERATOR) ++gencount; else if (rt == RobotType.SOLDIER) ++soldiercount; else ++othercount; } double decay = .8; if (rc.hasUpgrade(Upgrade.FUSION)) { decay = .99; } if ((40 + (10 * gencount) - (1.6 * soldiercount) - (1 * othercount)) * decay < 1) { return true; } return false; }
private static void shallWeAllIn() throws GameActionException { if (rc.senseEnemyNukeHalfDone() && Clock.getRoundNum() < 300) { rc.broadcast(Constants.attackChannel, Constants.attackAllIn); return; } int massedRobos = 0; double massedAmountNeeded = .5 * (40 + (10 * gencount) - (1 * othercount)); if (rc.senseEnemyNukeHalfDone()) massedAmountNeeded -= 10; int rallyRadius = 33; if (massedAmountNeeded > 50) rallyRadius = 63; Robot[] robos = rc.senseNearbyGameObjects(Robot.class, findRallyPoint(), rallyRadius, rc.getTeam()); for (Robot r : robos) { if (rc.senseRobotInfo(r).type == RobotType.SOLDIER) { ++massedRobos; } } if (massedRobos > massedAmountNeeded) // if we should all in... { rc.broadcast(Constants.attackChannel, Constants.attackAllIn); allInRound = Clock.getRoundNum(); } }
@Override public void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); if (savedInstanceState != null) { clock.setPlayer1Remaining(savedInstanceState.getLong(PLAYER_1_REMAINING, 25 * 60 * 1000)); clock.setPlayer2Remaining(savedInstanceState.getLong(PLAYER_2_REMAINING, 25 * 60 * 1000)); } }
@Test public void shouldBeAbleToAdvanceClockTimeOnEachQuery() throws Exception { Date startOfTheCentury = ymdDateFormat.parse("2000-01-01"); new DateAlteringClock(startOfTheCentury).advanceMillisOnEachQuery(); assertThat(Clock.currentTimeInMillis(), is(startOfTheCentury.getTime() + 1)); assertThat(Clock.currentTimeInMillis(), is(startOfTheCentury.getTime() + 2)); assertThat(Clock.currentTimeInMillis(), is(startOfTheCentury.getTime() + 3)); }
/** * Times and records the duration of event. * * @param event a {@link Callable} whose {@link Callable#call()} method implements a process whose * duration should be timed * @param <T> the type of the value returned by {@code event} * @return the value returned by {@code event} * @throws Exception if {@code event} throws an {@link Exception} */ public <T> T time(Callable<T> event) throws Exception { final long startTime = clock.tick(); try { return event.call(); } finally { update(clock.tick() - startTime); } }
@Test public void testNotEquals() throws Exception { String Id1 = "1"; String Id2 = "2"; Clock clock1 = new Clock(Id1); clock1.addNode(Id2, 2); Clock clock2 = new Clock(Id2); clock2.addNode(Id1, 1); Assert.assertTrue(!clock1.equals(clock2)); }
/** * Stop the time for this event. If the event haven't been started yet, the start and stop time * will be the same. */ public void stop() { if (isActive()) { mStop = mClock.now(); } else if (!isStarted()) { long now = mClock.now(); mStart = now; mStop = now; } mStopped = true; }
private static TimeBox generateTimeSpanForDay(Integer notUsed, Clock clock) { DateTime start; DateTime end; start = clock.getTime().withTime(0, 0, 0, 0); end = clock.getTime().withTime(23, 59, 59, 99); return new TimeBox(start, end); }
private static TimeBox generateTimeSpanForWeek(Integer unit, Clock clock) { DateTime start; DateTime end; start = clock.getTime().withDayOfWeek(1).withTime(0, 0, 0, 0); end = clock.createDate(start.plusWeeks(unit - 1).withDayOfWeek(5).withTime(23, 59, 59, 99)); return new TimeBox(start, end); }
@Override public void onPause() { super.onPause(); clock.pause(); handler.removeCallbacks(updateTimeDisplayTask); Editor editor = prefs.edit(); editor.putLong(PLAYER_1_REMAINING, clock.getPlayer1Remaining()); editor.putLong(PLAYER_2_REMAINING, clock.getPlayer2Remaining()); editor.commit(); }
public static TimeBox generateLastMonth(Clock clock) { DateTime start; DateTime end; start = clock.getTime().minusMonths(1).withDayOfMonth(1).withTime(0, 0, 0, 0); end = clock.createDate(start.plusMonths(1).minusDays(1).withTime(23, 59, 59, 99)); return new TimeBox(start, end); }
public static void main(String[] args) { // on initialise un objet clock Clock hms = new Clock(15, 55, 59); // test des Getters System.out.println("Test des Getters :"); System.out.println(hms.getHours()); System.out.println(hms.getMinutes()); System.out.println(hms.getSeconds()); // test de la conversion en secondes System.out.println("Test de la conversion en secondes :"); int seconds = 0; seconds = hms.convert2seconds(); System.out.println(seconds); // test de l'incrémentation. System.out.println("Test de l'incrémentation :"); String toStrong; hms.increments(); toStrong = hms.toString(); System.out.println(toStrong); // test du reset. System.out.println("Test du reset :"); hms.reset(); toStrong = hms.toString(); System.out.println(toStrong); }
public static void timerEnd(String message) { int endBytecodeNum = Clock.getBytecodeNum(); int endRoundNum = Clock.getRoundNum(); if (endRoundNum == startRoundNum) System.out.format( "timed %s: took %d bytecodes\n", message, endBytecodeNum - startBytecodeNum); else System.out.format( "timed %s: took %d turns + %d bytecodes\n", message, endRoundNum - startRoundNum, endBytecodeNum - startBytecodeNum); }
@Test public void testEquivalent() throws Exception { String Id1 = "1"; String Id2 = "2"; Clock cl1 = new Clock(Id1); Clock cl2 = new Clock(Id2); cl1.addNode(Id1, 1); cl1.addNode(Id2, 2); // cl1 = {1,2} cl2.addNode(Id1, 2); cl2.addNode(Id2, 1); // cl2 = {2,1} Assert.assertTrue(cl2.equivalent(cl1)); }
@Test public void currentClockTimeInMillisShouldTickOnFromZero() throws Exception { Date endOfTheDecade = ymdDateFormat.parse("2010-12-31"); new DateAlteringClock(endOfTheDecade); long before = 0, after = 0; while (after == before) { after = Clock.currentTimeInMillis(); if (before == 0) { before = after; } } assertTrue(Clock.currentTimeInMillis() - endOfTheDecade.getTime() < 1000); }
private static TimeBox generateTimeSpanForMonth(Integer unit, Clock clock, TimeBox next) { DateTime start; DateTime end; start = clock.createDate(next.getEnd().plusWeeks(1).withDayOfWeek(1).withTime(0, 0, 0, 0)); end = clock.createDate( start.plusMonths(unit).withDayOfWeek(1).minusDays(3).withTime(23, 59, 59, 99)); return new TimeBox(start, end); }
public static void loop(RobotController theRC) throws GameActionException { Clock.yield(); Bot.init(theRC); init(); while (true) { try { turn(); } catch (Exception e) { e.printStackTrace(); } Clock.yield(); } }
private static void turn() throws GameActionException { if (rc.getHealth() <= 6 * RobotType.SOLDIER.attackPower) { MessageBoard.PASTR_DISTRESS_SIGNAL.writeInt(Clock.getRoundNum()); } // do speculative pathing calculations int bytecodeLimit = 9000; MapLocation[] enemyPastrs = rc.sensePastrLocations(them); for (int i = 0; i < enemyPastrs.length; i++) { if (Clock.getBytecodeNum() > bytecodeLimit) break; Bfs.work(enemyPastrs[i], Bfs.PRIORITY_LOW, bytecodeLimit); } }
public long persistSelectedPipelines( String id, Long userId, List<String> selectedPipelines, boolean isBlacklist) { PipelineSelections pipelineSelections = findOrCreateCurrentPipelineSelectionsFor(id, userId); if (isBlacklist) { List<String> unselectedPipelines = invertSelections(selectedPipelines); pipelineSelections.update(unselectedPipelines, clock.currentTime(), userId, isBlacklist); } else { pipelineSelections.update(selectedPipelines, clock.currentTime(), userId, isBlacklist); } return pipelineRepository.saveSelectedPipelines(pipelineSelections); }
// HQ or pastr calls this function to spend spare bytecodes computing paths for soldiers public static void work(MapLocation dest, int priority, int bytecodeLimit) throws GameActionException { int page = findFreePage(dest, priority); Debug.indicate("path", 1, "BFS Pathing to " + dest.toString() + "; using page " + page); if (page == -1) return; // We can't do any work, or don't have to if (!dest.equals(previousDest)) { Debug.indicate("path", 0, "BFS initingQueue"); initQueue(dest); } else { Debug.indicate("path", 0, "BFS queue already inited"); } previousDest = dest; previousRoundWorked = Clock.getRoundNum(); previousPage = page; int mapWidth = rc.getMapWidth(); int mapHeight = rc.getMapHeight(); MapLocation enemyHQ = rc.senseEnemyHQLocation(); boolean destInSpawn = dest.distanceSquaredTo(enemyHQ) <= 25; while (locQueueHead != locQueueTail && Clock.getBytecodeNum() < bytecodeLimit) { // pop a location from the queue MapLocation loc = locQueue[locQueueHead]; locQueueHead++; int locX = loc.x; int locY = loc.y; for (int i = 8; i-- > 0; ) { int x = locX + dirsX[i]; int y = locY + dirsY[i]; if (x >= 0 && y >= 0 && x < mapWidth && y < mapHeight && !wasQueued[x][y]) { MapLocation newLoc = new MapLocation(x, y); if (rc.senseTerrainTile(newLoc) != TerrainTile.VOID && (destInSpawn || !Bot.isInTheirHQAttackRange(newLoc))) { publishResult(page, newLoc, dest, dirs[i]); // push newLoc onto queue locQueue[locQueueTail] = newLoc; locQueueTail++; wasQueued[x][y] = true; } } } } boolean finished = locQueueHead == locQueueTail; Debug.indicate("path", 2, "BFS finished = " + finished + "; locQueueHead = " + locQueueHead); writePageMetadata(page, Clock.getRoundNum(), dest, priority, finished); }
/** Starts the game running. */ private void startGame() { /* * Initialize everything we're going to be using. */ this.random = new Random(); this.snake = new LinkedList<>(); this.directions = new LinkedList<>(); this.logicTimer = new Clock(9.0f); this.isNewGame = true; // Set the timer to paused initially. logicTimer.setPaused(true); /* * This is the game loop. It will update and render the game and will * continue to run until the game window is closed. */ while (true) { // Get the current frame's start time. long start = System.nanoTime(); // Update the logic timer. logicTimer.update(); /* * If a cycle has elapsed on the logic timer, then update the game. */ if (logicTimer.hasElapsedCycle()) { updateGame(); } // Repaint the board and side panel with the new content. board.repaint(); side.repaint(); /* * Calculate the delta time between since the start of the frame * and sleep for the excess time to cap the frame rate. While not * incredibly accurate, it is sufficient for our purposes. */ long delta = (System.nanoTime() - start) / 1000000L; if (delta < FRAME_TIME) { try { Thread.sleep(FRAME_TIME - delta); } catch (Exception e) { e.printStackTrace(); } } } }
@Test public void shouldBeAbleToFreezeClockTime() throws Exception { SystemClock systemClock = new SystemClock(); long before = 0, after = 0; new DateAlteringClock(systemClock.currentClockDate()).freeze(); long frozenTime = Clock.currentTimeInMillis(); while (after == before) { after = systemClock.currentClockTimeInMillis(); if (before == 0) { before = after; } } assertThat(Clock.currentTimeInMillis(), is(frozenTime)); }
private static TimeBox generateTimeSpanForDay(Integer unit, Clock clock, TimeBox next) { DateTime start; DateTime end; int nextDay = clock.createDate(next.getEnd()).getDayOfWeek(); if (nextDay > 5) start = clock.createDate(next.getEnd().plusWeeks(1).withDayOfWeek(1).withTime(0, 0, 0, 0)); else start = clock.createDate(next.getEnd().plusDays(1).withTime(0, 0, 0, 0)); end = clock.getTime().withTime(23, 59, 59, 99); return new TimeBox(start, end); }
private static void runMissile() { int lastTurn = Clock.getRoundNum() + GameConstants.MISSILE_LIFESPAN; int[] damageRange = {0, 8, 15, 24, 35, 48}; MapLocation target = null; boolean targetMoves = true; while (true) { myLoc = rc.getLocation(); int turns = lastTurn - Clock.getRoundNum(); if (targetMoves) { // Re-acquire the target's location RobotInfo[] inRange = rc.senseNearbyRobots(damageRange[turns], enemyTeam); if (inRange.length > 0) { // No units to target target = inRange[0].location; targetMoves = inRange[0].type.canMove(); rc.setIndicatorString(0, "Missile targetting " + inRange[0].type + "@" + target); } else { targetMoves = false; // Pick a tower or the HQ MapLocation[] enemyTowers = rc.senseEnemyTowerLocations(); for (MapLocation t : enemyTowers) { if (myLoc.distanceSquaredTo(t) <= damageRange[turns]) { target = t; rc.setIndicatorString(0, "Missile targetting Tower @" + target); break; } } if (target == null) { target = rc.senseEnemyHQLocation(); rc.setIndicatorString(0, "Missile targetting HQ @" + target); } } } try { if (target != null) { if (myLoc.distanceSquaredTo(target) <= GameConstants.MISSILE_RADIUS_SQUARED) rc.explode(); else { Direction d = myLoc.directionTo(target); if (rc.canMove(d)) rc.move(d); else if (rc.canMove(d.rotateLeft())) rc.move(d.rotateLeft()); else if (rc.canMove(d.rotateRight())) rc.move(d.rotateRight()); } } } catch (GameActionException e) { System.out.println("Missile exception"); // e.printStackTrace(); } rc.yield(); } }
/** * Clears all the logs in userlog directory. * * <p>Adds the job directories for deletion with default retain hours. Deletes all other * directories, if any. This is usually called on reinit/restart of the TaskTracker * * @param conf * @throws IOException */ void clearOldUserLogs(Configuration conf) throws IOException { File userLogDir = TaskLog.getUserLogDir(); if (userLogDir.exists()) { String[] logDirs = userLogDir.list(); if (logDirs.length > 0) { // add all the log dirs to taskLogsMnonitor. long now = clock.getTime(); for (String logDir : logDirs) { if (logDir.equals(logAsyncDisk.TOBEDELETED)) { // skip this continue; } JobID jobid = null; try { jobid = JobID.forName(logDir); } catch (IllegalArgumentException ie) { // if the directory is not a jobid, delete it immediately deleteLogPath(new File(userLogDir, logDir).getAbsolutePath()); continue; } // add the job log directory with default retain hours, if it is not // already added if (!completedJobs.containsKey(jobid)) { markJobLogsForDeletion(now, conf, jobid); } } } } }
/** Updates the game's logic. */ private void updateGame() { /* * Gets the type of tile that the head of the snake collided with. If * the snake hit a wall, SnakeBody will be returned, as both conditions * are handled identically. */ TileType collision = updateSnake(); /* * Here we handle the different possible collisions. * * Fruit: If we collided with a fruit, we increment the number of * fruits that we've eaten, update the score, and spawn a new fruit. * * SnakeBody: If we collided with our tail (or a wall), we flag that * the game is over and pause the game. * * If no collision occurred, we simply decrement the number of points * that the next fruit will give us if it's high enough. This adds a * bit of skill to the game as collecting fruits more quickly will * yield a higher score. */ if (collision == TileType.Fruit) { fruitsEaten++; score += nextFruitScore; spawnFruit(); } else if (collision == TileType.SnakeBody) { isGameOver = true; logicTimer.setPaused(true); } else if (nextFruitScore > 10) { nextFruitScore--; } }
private void rescaleIfNeeded() { final long now = clock.getTick(); final long next = nextScaleTime.get(); if (now >= next) { rescale(now, next); } }