private void resetState() { connectLatch.drainPermits(); abandonLatch.drainPermits(); bindLatch.drainPermits(); searchLatch.drainPermits(); closeLatch.drainPermits(); context.set(null); serverConnection = mock(ServerConnection.class); }
/** Run the bollie thread */ @Override public void run() { golfBall[] ballsCollected; // Array to hold the balls bollie collects while (done.get() != true) { // Check that Range has not closed try { sleep(waitTime.nextInt(5000) + 2000); // Sleep for 2-7 seconds if (done.get() != true) { // Recheck condition for closing, just in case! bollieOnField.set(true); // Set Atomic boolean to true System.out.println("*********** Bollie collecting balls ************"); ballsCollected = sharedField .collectAllBallsFromField(); // Collect balls, no golfers allowed to swing while // this is happening semaphore.drainPermits(); // drain permits so that golfers must wait System.out.println( "*********** Bollie collected " + ballsCollected.length + " balls ************"); sleep(1000); // Simulate collecting and adding sharedStash.addBallsToStash(ballsCollected); // Add collected balls to stash semaphore.release( noGolfers); // Release semaphore and all waiting threads, so that golfers waiting can // continue to their next swing bollieOnField.set(false); // Set Atomic boolean to false, condition no longer blocked } } catch (InterruptedException e) { e.printStackTrace(); } } sharedStash.golfersGo(); }
@Override protected void doJob() throws Exception { // log.debug("doJob()"); temperatureBufferBlockMap.allocate(); boolean localHalt = shouldHalt; while (!localHalt) { try { jobsToDoSemaphore.acquire(); jobsToDoSemaphore.drainPermits(); if (SampleCache.DEBUG_SAMPLE_CACHE_ACTIVITY) { log.trace("Attempting to refresh cache."); } sampleCache.refreshCache(); } catch (final InterruptedException ie) { // Don't care, probably woken up to shutdown } catch (final Exception e) { if (log.isErrorEnabled()) { log.error("Exception caught during cache population run: " + e.toString(), e); } } localHalt = shouldHalt; } }
protected void leaveHome() { currentBuilding = cityData.buildings.get(home.buildingNumber); if (personGui.isInBedroom()) { personGui.DoAlmostWall(); try { isMoving.acquire(); } catch (InterruptedException e) { // Auto-generated catch block e.printStackTrace(); } personGui.DoGoToWall(); try { isMoving.acquire(); } catch (InterruptedException e) { // Auto-generated catch block e.printStackTrace(); } } if (home instanceof Home) { personGui.DoGoToEntrance(); atEntrance.drainPermits(); try { atEntrance.acquire(); } catch (InterruptedException e) { // Auto-generated catch block e.printStackTrace(); } personGui.DoLeaveBuilding(); currentBuilding.LeaveBuilding(this); } if (home instanceof Apartment) { Apartment a = (Apartment) home; personGui.DoGoToEntrance(); try { isMoving.acquire(); } catch (InterruptedException e1) { // Auto-generated catch block e1.printStackTrace(); } a.rooms.get(roomNumber).LeaveBuilding(this); personGui.DoGoToHallway(); try { isMoving.acquire(); } catch (InterruptedException e) { // Auto-generated catch block e.printStackTrace(); } personGui.DoLeaveBuilding(); a.LeaveBuilding(this); } bigState = BigState.doingNothing; }
protected void goToMarket() { int marketNumber = 0; destinationBuilding = cityData.markets.get(0); GoToDestination(); personGui.DoGoToBuilding(19); currentBuilding = cityData.buildings.get(19); atBuilding.drainPermits(); try { atBuilding.acquire(); } catch (InterruptedException e) { // Auto-generated catch block e.printStackTrace(); } personGui.DoGoIntoBuilding(); currentBuilding.EnterBuilding(this, desiredRole); }
protected void goToBank() { int bankNumber = 0; destinationBuilding = cityData.banks.get(bankNumber); GoToDestination(); personGui.DoGoToBuilding(18); currentBuilding = cityData.buildings.get(18); atBuilding.drainPermits(); try { atBuilding.acquire(); if (currentBuilding.type == BuildingType.bank) print("made it past at Building acquire"); } catch (InterruptedException e) { // Auto-generated catch block e.printStackTrace(); } personGui.DoGoIntoBuilding(); print("entering the building and desired role is " + desiredRole); currentBuilding.EnterBuilding(this, desiredRole); }
public synchronized String getJSValue(String expression) { // Don't try to evaluate js code again if the binding has already been destroyed if (!destroyed) { // see if this is an expression or a statement block // Match ; followed by 0 or even quotes Pattern pattern = Pattern.compile(";(?=([^\"]*\"[^\"]*\")*[^\"]*$)"); Matcher matcher = pattern.matcher(expression); if (matcher.find()) { String lastStmt = expression.substring(matcher.end(matcher.groupCount() - 1)); String stmtBlock = expression.substring(0, matcher.end(matcher.groupCount() - 1)); expression = stmtBlock + " return " + lastStmt; } else { expression = " return " + expression; } String code = "_TiReturn.setValue((function(){try{" + expression + "+\"\";}catch(ti_eval_err){return '';}})());"; Log.d(TAG, "getJSValue:" + code, Log.DEBUG_MODE); returnSemaphore.drainPermits(); synchronized (codeSnippets) { codeSnippets.push(code); } try { if (!returnSemaphore.tryAcquire(3500, TimeUnit.MILLISECONDS)) { synchronized (codeSnippets) { codeSnippets.removeElement(code); } Log.w(TAG, "Timeout waiting to evaluate JS"); } return returnValue; } catch (InterruptedException e) { Log.e(TAG, "Interrupted", e); } } return null; }
/** * Sets <CODE>playerLocation</CODE>. * * @param loc the location to be used to set the player location */ private void setPlayerLocation(Location loc) { lock.drainPermits(); // Remove all permits playerLocation = loc; lock.release(); // Allow getPlayerMove to run once }
@Test public void testTruncatedLog() throws Exception { try { DirectUpdateHandler2.commitOnClose = false; final Semaphore logReplay = new Semaphore(0); final Semaphore logReplayFinish = new Semaphore(0); UpdateLog.testing_logReplayHook = new Runnable() { @Override public void run() { try { assertTrue(logReplay.tryAcquire(timeout, TimeUnit.SECONDS)); } catch (Exception e) { throw new RuntimeException(e); } } }; UpdateLog.testing_logReplayFinishHook = new Runnable() { @Override public void run() { logReplayFinish.release(); } }; String logDir = h.getCore().getUpdateHandler().getUpdateLog().getLogDir(); clearIndex(); assertU(commit()); assertU(adoc("id", "F1")); assertU(adoc("id", "F2")); assertU(adoc("id", "F3")); h.close(); String[] files = HdfsUpdateLog.getLogList(fs, new Path(logDir)); Arrays.sort(files); FSDataOutputStream dos = fs.append(new Path(logDir, files[files.length - 1])); dos.writeLong(0xffffffffffffffffL); dos.writeChars( "This should be appended to a good log file, representing a bad partially written record."); dos.close(); logReplay.release(1000); logReplayFinish.drainPermits(); ignoreException( "OutOfBoundsException"); // this is what the corrupted log currently produces... subject // to change. createCore(); assertTrue(logReplayFinish.tryAcquire(timeout, TimeUnit.SECONDS)); resetExceptionIgnores(); assertJQ(req("q", "*:*"), "/response/numFound==3"); // // Now test that the bad log file doesn't mess up retrieving latest versions // updateJ( jsonAdd(sdoc("id", "F4", "_version_", "104")), params(DISTRIB_UPDATE_PARAM, FROM_LEADER)); updateJ( jsonAdd(sdoc("id", "F5", "_version_", "105")), params(DISTRIB_UPDATE_PARAM, FROM_LEADER)); updateJ( jsonAdd(sdoc("id", "F6", "_version_", "106")), params(DISTRIB_UPDATE_PARAM, FROM_LEADER)); // This currently skips the bad log file and also returns the version of the clearIndex (del // *:*) // assertJQ(req("qt","/get", "getVersions","6"), "/versions==[106,105,104]"); assertJQ(req("qt", "/get", "getVersions", "3"), "/versions==[106,105,104]"); } finally { DirectUpdateHandler2.commitOnClose = true; UpdateLog.testing_logReplayHook = null; UpdateLog.testing_logReplayFinishHook = null; } }
@Test public void testBuffering() throws Exception { DirectUpdateHandler2.commitOnClose = false; final Semaphore logReplay = new Semaphore(0); final Semaphore logReplayFinish = new Semaphore(0); UpdateLog.testing_logReplayHook = new Runnable() { @Override public void run() { try { assertTrue(logReplay.tryAcquire(timeout, TimeUnit.SECONDS)); } catch (Exception e) { throw new RuntimeException(e); } } }; UpdateLog.testing_logReplayFinishHook = new Runnable() { @Override public void run() { logReplayFinish.release(); } }; SolrQueryRequest req = req(); UpdateHandler uhandler = req.getCore().getUpdateHandler(); UpdateLog ulog = uhandler.getUpdateLog(); try { clearIndex(); assertU(commit()); assertEquals(UpdateLog.State.ACTIVE, ulog.getState()); ulog.bufferUpdates(); assertEquals(UpdateLog.State.BUFFERING, ulog.getState()); Future<UpdateLog.RecoveryInfo> rinfoFuture = ulog.applyBufferedUpdates(); assertTrue(rinfoFuture == null); assertEquals(UpdateLog.State.ACTIVE, ulog.getState()); ulog.bufferUpdates(); assertEquals(UpdateLog.State.BUFFERING, ulog.getState()); // simulate updates from a leader updateJ( jsonAdd(sdoc("id", "B1", "_version_", "1010")), params(DISTRIB_UPDATE_PARAM, FROM_LEADER)); updateJ( jsonAdd(sdoc("id", "B11", "_version_", "1015")), params(DISTRIB_UPDATE_PARAM, FROM_LEADER)); updateJ( jsonDelQ("id:B1 id:B11 id:B2 id:B3"), params(DISTRIB_UPDATE_PARAM, FROM_LEADER, "_version_", "-1017")); updateJ( jsonAdd(sdoc("id", "B2", "_version_", "1020")), params(DISTRIB_UPDATE_PARAM, FROM_LEADER)); updateJ( jsonAdd(sdoc("id", "B3", "_version_", "1030")), params(DISTRIB_UPDATE_PARAM, FROM_LEADER)); deleteAndGetVersion("B1", params(DISTRIB_UPDATE_PARAM, FROM_LEADER, "_version_", "-2010")); assertJQ( req("qt", "/get", "getVersions", "6"), "=={'versions':[-2010,1030,1020,-1017,1015,1010]}"); assertU(commit()); assertJQ( req("qt", "/get", "getVersions", "6"), "=={'versions':[-2010,1030,1020,-1017,1015,1010]}"); // updates should be buffered, so we should not see any results yet. assertJQ(req("q", "*:*"), "/response/numFound==0"); // real-time get should also not show anything (this could change in the future, // but it's currently used for validating version numbers too, so it would // be bad for updates to be visible if we're just buffering. assertJQ(req("qt", "/get", "id", "B3"), "=={'doc':null}"); rinfoFuture = ulog.applyBufferedUpdates(); assertTrue(rinfoFuture != null); assertEquals(UpdateLog.State.APPLYING_BUFFERED, ulog.getState()); logReplay.release(1000); UpdateLog.RecoveryInfo rinfo = rinfoFuture.get(); assertEquals(UpdateLog.State.ACTIVE, ulog.getState()); assertJQ( req("qt", "/get", "getVersions", "6"), "=={'versions':[-2010,1030,1020,-1017,1015,1010]}"); assertJQ(req("q", "*:*"), "/response/numFound==2"); // move back to recovering ulog.bufferUpdates(); assertEquals(UpdateLog.State.BUFFERING, ulog.getState()); Long ver = getVer(req("qt", "/get", "id", "B3")); assertEquals(1030L, ver.longValue()); // add a reordered doc that shouldn't overwrite one in the index updateJ( jsonAdd(sdoc("id", "B3", "_version_", "3")), params(DISTRIB_UPDATE_PARAM, FROM_LEADER)); // reorder two buffered updates updateJ( jsonAdd(sdoc("id", "B4", "_version_", "1040")), params(DISTRIB_UPDATE_PARAM, FROM_LEADER)); deleteAndGetVersion( "B4", params( DISTRIB_UPDATE_PARAM, FROM_LEADER, "_version_", "-940")); // this update should not take affect updateJ( jsonAdd(sdoc("id", "B6", "_version_", "1060")), params(DISTRIB_UPDATE_PARAM, FROM_LEADER)); updateJ( jsonAdd(sdoc("id", "B5", "_version_", "1050")), params(DISTRIB_UPDATE_PARAM, FROM_LEADER)); updateJ( jsonAdd(sdoc("id", "B8", "_version_", "1080")), params(DISTRIB_UPDATE_PARAM, FROM_LEADER)); // test that delete by query is at least buffered along with everything else so it will delete // the // currently buffered id:8 (even if it doesn't currently support versioning) updateJ( "{\"delete\": { \"query\":\"id:B2 OR id:B8\" }}", params(DISTRIB_UPDATE_PARAM, FROM_LEADER, "_version_", "-3000")); assertJQ( req("qt", "/get", "getVersions", "13"), "=={'versions':[-3000,1080,1050,1060,-940,1040,3,-2010,1030,1020,-1017,1015,1010]}" // the // "3" // appears because versions aren't checked while buffering ); logReplay.drainPermits(); rinfoFuture = ulog.applyBufferedUpdates(); assertTrue(rinfoFuture != null); assertEquals(UpdateLog.State.APPLYING_BUFFERED, ulog.getState()); // apply a single update logReplay.release(1); // now add another update updateJ( jsonAdd(sdoc("id", "B7", "_version_", "1070")), params(DISTRIB_UPDATE_PARAM, FROM_LEADER)); // a reordered update that should be dropped deleteAndGetVersion("B5", params(DISTRIB_UPDATE_PARAM, FROM_LEADER, "_version_", "-950")); deleteAndGetVersion("B6", params(DISTRIB_UPDATE_PARAM, FROM_LEADER, "_version_", "-2060")); logReplay.release(1000); UpdateLog.RecoveryInfo recInfo = rinfoFuture.get(); assertJQ( req("q", "*:*", "sort", "id asc", "fl", "id,_version_"), "/response/docs==[" + "{'id':'B3','_version_':1030}" + ",{'id':'B4','_version_':1040}" + ",{'id':'B5','_version_':1050}" + ",{'id':'B7','_version_':1070}" + "]"); assertEquals(1, recInfo.deleteByQuery); assertEquals( UpdateLog.State.ACTIVE, ulog.getState()); // leave each test method in a good state } finally { DirectUpdateHandler2.commitOnClose = true; UpdateLog.testing_logReplayHook = null; UpdateLog.testing_logReplayFinishHook = null; req().close(); } }
// in rare circumstances, two logs can be left uncapped (lacking a commit at the end signifying // that all the content in the log was committed) @Test public void testRecoveryMultipleLogs() throws Exception { try { DirectUpdateHandler2.commitOnClose = false; final Semaphore logReplay = new Semaphore(0); final Semaphore logReplayFinish = new Semaphore(0); UpdateLog.testing_logReplayHook = new Runnable() { @Override public void run() { try { assertTrue(logReplay.tryAcquire(timeout, TimeUnit.SECONDS)); } catch (Exception e) { throw new RuntimeException(e); } } }; UpdateLog.testing_logReplayFinishHook = new Runnable() { @Override public void run() { logReplayFinish.release(); } }; String logDir = h.getCore().getUpdateHandler().getUpdateLog().getLogDir(); clearIndex(); assertU(commit()); assertU(adoc("id", "AAAAAA")); assertU(adoc("id", "BBBBBB")); assertU(adoc("id", "CCCCCC")); h.close(); String[] files = HdfsUpdateLog.getLogList(fs, new Path(logDir)); Arrays.sort(files); String fname = files[files.length - 1]; FSDataOutputStream dos = fs.append(new Path(logDir, files[files.length - 1])); dos.writeLong(0xffffffffffffffffL); dos.writeChars( "This should be appended to a good log file, representing a bad partially written record."); dos.close(); FSDataInputStream dis = fs.open(new Path(logDir, files[files.length - 1])); byte[] content = new byte[(int) dis.available()]; dis.readFully(content); dis.close(); // Now make a newer log file with just the IDs changed. NOTE: this may not work if log format // changes too much! findReplace( "AAAAAA".getBytes(StandardCharsets.UTF_8), "aaaaaa".getBytes(StandardCharsets.UTF_8), content); findReplace( "BBBBBB".getBytes(StandardCharsets.UTF_8), "bbbbbb".getBytes(StandardCharsets.UTF_8), content); findReplace( "CCCCCC".getBytes(StandardCharsets.UTF_8), "cccccc".getBytes(StandardCharsets.UTF_8), content); // WARNING... assumes format of .00000n where n is less than 9 long logNumber = Long.parseLong(fname.substring(fname.lastIndexOf(".") + 1)); String fname2 = String.format( Locale.ROOT, UpdateLog.LOG_FILENAME_PATTERN, UpdateLog.TLOG_NAME, logNumber + 1); dos = fs.create(new Path(logDir, fname2), (short) 1); dos.write(content); dos.close(); logReplay.release(1000); logReplayFinish.drainPermits(); ignoreException( "OutOfBoundsException"); // this is what the corrupted log currently produces... subject // to change. createCore(); assertTrue(logReplayFinish.tryAcquire(timeout, TimeUnit.SECONDS)); resetExceptionIgnores(); assertJQ(req("q", "*:*"), "/response/numFound==6"); } finally { DirectUpdateHandler2.commitOnClose = true; UpdateLog.testing_logReplayHook = null; UpdateLog.testing_logReplayFinishHook = null; } }
public void reset() { semaphore.drainPermits(); msg = null; }
@SuppressWarnings({"rawtypes", "unchecked"}) @Override public V call() { T value = source.getAttribute(sensor); // return immediately if either the ready predicate or the abort conditions hold if (ready(value)) return postProcess(value); final List<Exception> abortionExceptions = Lists.newCopyOnWriteArrayList(); long start = System.currentTimeMillis(); for (AttributeAndSensorCondition abortCondition : abortSensorConditions) { Object abortValue = abortCondition.source.getAttribute(abortCondition.sensor); if (abortCondition.predicate.apply(abortValue)) { abortionExceptions.add( new Exception( "Abort due to " + abortCondition.source + " -> " + abortCondition.sensor)); } } if (abortionExceptions.size() > 0) { throw new CompoundRuntimeException( "Aborted waiting for ready from " + source + " " + sensor, abortionExceptions); } TaskInternal<?> current = (TaskInternal<?>) Tasks.current(); if (current == null) throw new IllegalStateException("Should only be invoked in a running task"); Entity entity = BrooklynTaskTags.getTargetOrContextEntity(current); if (entity == null) throw new IllegalStateException( "Should only be invoked in a running task with an entity tag; " + current + " has no entity tag (" + current.getStatusDetail(false) + ")"); final LinkedList<T> publishedValues = new LinkedList<T>(); final Semaphore semaphore = new Semaphore(0); // could use Exchanger SubscriptionHandle subscription = null; List<SubscriptionHandle> abortSubscriptions = Lists.newArrayList(); try { subscription = entity .subscriptions() .subscribe( source, sensor, new SensorEventListener<T>() { @Override public void onEvent(SensorEvent<T> event) { synchronized (publishedValues) { publishedValues.add(event.getValue()); } semaphore.release(); } }); for (final AttributeAndSensorCondition abortCondition : abortSensorConditions) { abortSubscriptions.add( entity .subscriptions() .subscribe( abortCondition.source, abortCondition.sensor, new SensorEventListener<Object>() { @Override public void onEvent(SensorEvent<Object> event) { if (abortCondition.predicate.apply(event.getValue())) { abortionExceptions.add( new Exception( "Abort due to " + abortCondition.source + " -> " + abortCondition.sensor)); semaphore.release(); } } })); Object abortValue = abortCondition.source.getAttribute(abortCondition.sensor); if (abortCondition.predicate.apply(abortValue)) { abortionExceptions.add( new Exception( "Abort due to " + abortCondition.source + " -> " + abortCondition.sensor)); } } if (abortionExceptions.size() > 0) { throw new CompoundRuntimeException( "Aborted waiting for ready from " + source + " " + sensor, abortionExceptions); } CountdownTimer timer = timeout != null ? timeout.countdownTimer() : null; Duration maxPeriod = ValueResolver.PRETTY_QUICK_WAIT; Duration nextPeriod = ValueResolver.REAL_QUICK_PERIOD; while (true) { // check the source on initial run (could be done outside the loop) // and also (optionally) on each iteration in case it is more recent value = source.getAttribute(sensor); if (ready(value)) break; if (timer != null) { if (timer.getDurationRemaining().isShorterThan(nextPeriod)) { nextPeriod = timer.getDurationRemaining(); } if (timer.isExpired()) { if (onTimeout.isPresent()) return onTimeout.get(); throw new RuntimeTimeoutException("Unsatisfied after " + Duration.sinceUtc(start)); } } String prevBlockingDetails = current.setBlockingDetails(blockingDetails); try { if (semaphore.tryAcquire(nextPeriod.toMilliseconds(), TimeUnit.MILLISECONDS)) { // immediately release so we are available for the next check semaphore.release(); // if other permits have been made available (e.g. multiple notifications) drain them // all as no point running multiple times semaphore.drainPermits(); } } finally { current.setBlockingDetails(prevBlockingDetails); } // check any subscribed values which have come in first while (true) { synchronized (publishedValues) { if (publishedValues.isEmpty()) break; value = publishedValues.pop(); } if (ready(value)) break; } // if unmanaged then ignore the other abort conditions if (!ignoreUnmanaged && Entities.isNoLongerManaged(entity)) { if (onUnmanaged.isPresent()) return onUnmanaged.get(); throw new NotManagedException(entity); } if (abortionExceptions.size() > 0) { throw new CompoundRuntimeException( "Aborted waiting for ready from " + source + " " + sensor, abortionExceptions); } nextPeriod = nextPeriod.times(2).upperBound(maxPeriod); } if (LOG.isDebugEnabled()) LOG.debug("Attribute-ready for {} in entity {}", sensor, source); return postProcess(value); } catch (InterruptedException e) { throw Exceptions.propagate(e); } finally { if (subscription != null) { entity.subscriptions().unsubscribe(subscription); } for (SubscriptionHandle handle : abortSubscriptions) { entity.subscriptions().unsubscribe(handle); } } }
@Override public void run() { final Semaphore sem = new Semaphore(0); final List<String> logs = new ArrayList<String>(); final Map<String, List<String>> logsToSync = new HashMap<String, List<String>>(); final List<Session> sessions = new ArrayList<Session>(); GenericWebsocketClient gwc = new GenericWebsocketClient( new WebsocketClient() { @Override public void onOpen(final Session session, EndpointConfig config) { try { sessions.add(session); String sid = session.getId(); List<String> sl = Collections.synchronizedList(new ArrayList<String>(logs)); logsToSync.put(sid, sl); for (String id : sl) { AttLog log = attLogsManager.findById(id); String json = attLogSerializer.toJson(log); String cmdJson = "attLog;" + json; logger.info(cmdJson); session.getBasicRemote().sendText(cmdJson); } } catch (Exception e) { logger.log(Level.SEVERE, e.getMessage(), e); sem.release(); } } @Override public void onClose(Session s, CloseReason reason) { logger.info("onClose"); sem.release(); } @Override public void onMessage(String m, Session session) { logger.info("onMessage " + m); String sid = session.getId(); List<String> sl = logsToSync.get(sid); String cmd = "OK;delete;"; if (m.startsWith(cmd)) { String id = m.substring(cmd.length()); try { attLogsManager.remove(id); if (sl != null) { sl.remove(id); } if (sl == null || sl.size() <= 0) { sem.release(); } } catch (AttLogException e) { logger.log(Level.SEVERE, e.getMessage(), e); sem.release(); } } } }); final URI uri = URI.create("ws://" + serverData.getIp() + ":" + serverData.getPort() + serverData.getUrl()); while (true) { // busco a ver si existen logs a ser sincronizados. logs.clear(); try { List<String> ls = attLogsManager.findAll(); if (ls != null && ls.size() > 0) { logs.addAll(ls); sem.drainPermits(); logger.info("connecting to : " + uri.toString()); ContainerProvider.getWebSocketContainer().connectToServer(gwc, uri); try { sem.acquire(); } catch (InterruptedException e1) { e1.printStackTrace(); } } } catch (DeploymentException | AttLogException e) { logger.log(Level.SEVERE, e.getMessage(), e); } catch (IOException e) { logger.log(Level.SEVERE, e.getMessage(), e); } catch (Exception e) { logger.log(Level.SEVERE, e.getMessage(), e); } // limpio todas las sesiones que hayan quedado habiertas. for (Session s : sessions) { try { if (s.isOpen()) { s.close(); } } catch (IOException e) { } } sessions.clear(); logsToSync.clear(); logs.clear(); try { // espero a que alguien marque o hasta que se cumpla el sleep. MutualExclusion.using[MutualExclusion.NEED_ATTLOGS_SYNC].tryAcquire( sleep, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { } } }
public void GoToDestination() { currGrid = cityData.cityGrid[personGui.getX() / 20][personGui.getY() / 20]; if (walk == true) { personGui.DoGoToBuilding(destinationBuilding.buildingNumber); // PersonGui.DoWalk(if you ever hit an RGrid, acquire it first, and then walk through, and // don't walk through bgrids) walking = true; while (walking) { if (crossingRoad) { try { currRGrid.occupied.acquire(); // System.out.println("1"); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { nextRGrid.occupied.acquire(); // System.out.println("2"); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } personGui.crossRoad(); try { gridding.acquire(); } catch (Exception e) { } currRGrid.occupied.release(); // System.out.println("1"); nextRGrid.occupied.release(); // System.out.println("0"); // ACQUIRE CURRENT AND NEXT } else { // // go from grid to grid // currGrid = nextGrid //// if undo //// if(curr instanceof RGrid) { //// person.acquire those next two semaphores in that direction //// personGui.crossRoad(direction); //// move to next //// release roads //// } // else { // //personGui.MoveToNextGrid; // } // print("hello"); personGui.MoveToNextGrid(currGrid); try { gridding.acquire(); } catch (Exception e) { } } } } if (car == true) { currentBuilding.closest.acquireGrid(); currRGrid = currentBuilding.closest; personGui.DoWalkToRGrid(currentBuilding.buildingNumber); // personGui.//acquire the semaphore of the // road(currentBuilding.closest.index1(),currentBuilding.closest.index2()) // then he moves like a bus until he gets to his destinatoin's rgrid, gets off road // then he releases last road semaphore isMoving.drainPermits(); try { isMoving.acquire(); } catch (Exception e) { } System.err.println("hello"); personGui.getInOrOutCar(); personGui.DriveToDestination(destinationBuilding); // personGui.DriveToClosestRGrid(destinationBuilding); **** have similar mechanisms to // busgridbehavior // if person's rgrid is destination.closestRgrid, then, walk to building driving = true; while (driving) { if (gridToAcquire != null) { MoveToGrid(); continue; } // puts this "mini-scheduler" to sleep try { isMoving.acquire(); } catch (Exception e) { } } // remember to release current and previous grids currRGrid.releaseGrid(); prevRGrid.releaseGrid(); gridToAcquire.releaseGrid(); // WALKT TO THE BUILDING NOW currRGrid = currentBuilding.closest; /*currRGrid = currentBuilding.closest; >>>>>>> 0a17ff0b1dfacf5cdfd33fa5a6faac8714cda482 //personGui.; driving = true; while(driving) { try { //.acquire(); } catch(Exception e){} personGui.getInOrOutCar(); //personGui.DriveToClosestRGrid(destinationBuilding); **** have similar mechanisms to busgridbehavior //if person's rgrid is destination.closestRgrid, then, walk to building try { isMoving.acquire(); } catch(Exception e){} driving = false; }*/ // personGui // have similar mechanisms to busgridbehavior // if person's rgrid is destination.closestRgrid, then, walk to building // YOU WILL TURN INTO A ROBOT } if (bus == true) { destinationBusStop = currentBuilding.busStop; personGui.DoGoToBusStop(destinationBusStop); try { isMoving.acquire(); } catch (Exception e) { } currentBusStop = destinationBusStop; destinationBusStop = destinationBuilding.busStop; currentBusStop.msgWaitingAtStop(this, destinationBusStop); try { isMoving.acquire(); } catch (Exception e) { } if (currentBus == null) { try { isMoving.acquire(); } catch (Exception e) { } } personGui.DoGoToBus(currentBus); try { isMoving.acquire(); } catch (Exception e) { } cityData.guis.remove(personGui); currentBus.msgOnBus(); try { isMoving.acquire(); } catch (Exception e) { } cityData.guis.add(personGui); personGui.setXPos(currentBus.getX()); personGui.setYPos(currentBus.getY()); currentBus.msgOnBus(); personGui.DoGoToBusStop(destinationBusStop); // THIS SHOULD ACQUIRE ROAD SEMAPHORE // if it needs to try { isMoving.acquire(); } catch (Exception e) { } } currentBuilding = destinationBuilding; }