List of usage examples for java.util.concurrent.atomic AtomicInteger get
public final int get()
From source file:com.github.podd.resources.test.UploadArtifactResourceImplTest.java
@Test public final void testLoadArtifactConcurrency() throws Exception { // load test artifact final InputStream inputStream4Artifact = this.getClass() .getResourceAsStream(TestConstants.TEST_ARTIFACT_IMPORT_PSCIENCEv1); Assert.assertNotNull("Could not find test resource: " + TestConstants.TEST_ARTIFACT_IMPORT_PSCIENCEv1, inputStream4Artifact);/*from ww w .j av a 2 s . com*/ final String nextTestArtifact = IOUtils.toString(inputStream4Artifact); final AtomicInteger threadSuccessCount = new AtomicInteger(0); final AtomicInteger perThreadSuccessCount = new AtomicInteger(0); final AtomicInteger threadStartCount = new AtomicInteger(0); final AtomicInteger perThreadStartCount = new AtomicInteger(0); final CountDownLatch openLatch = new CountDownLatch(1); // Changing this from 8 to 9 on my machine may be triggering a restlet // bug final int threadCount = 9; final int perThreadCount = 2; final CountDownLatch closeLatch = new CountDownLatch(threadCount); for (int i = 0; i < threadCount; i++) { final int number = i; final Runnable runner = new Runnable() { @Override public void run() { try { openLatch.await(55000, TimeUnit.MILLISECONDS); threadStartCount.incrementAndGet(); for (int j = 0; j < perThreadCount; j++) { perThreadStartCount.incrementAndGet(); ClientResource uploadArtifactClientResource = null; try { uploadArtifactClientResource = new ClientResource( UploadArtifactResourceImplTest.this .getUrl(PoddWebConstants.PATH_ARTIFACT_UPLOAD)); AbstractResourceImplTest.setupThreading(uploadArtifactClientResource.getContext()); final Representation input = UploadArtifactResourceImplTest.this .buildRepresentationFromResource( TestConstants.TEST_ARTIFACT_IMPORT_PSCIENCEv1, MediaType.APPLICATION_RDF_XML); final Representation results = UploadArtifactResourceImplTest.this .doTestAuthenticatedRequest(uploadArtifactClientResource, Method.POST, input, MediaType.APPLICATION_RDF_XML, Status.SUCCESS_OK, AbstractResourceImplTest.WITH_ADMIN); // verify: results (expecting the added // artifact's ontology IRI) final String body = UploadArtifactResourceImplTest.this.getText(results); final Collection<InferredOWLOntologyID> ontologyIDs = OntologyUtils .stringToOntologyID(body, RDFFormat.RDFXML); Assert.assertNotNull("No ontology IDs in response", ontologyIDs); Assert.assertEquals("More than 1 ontology ID in response", 1, ontologyIDs.size()); Assert.assertTrue("Ontology ID not of expected format", ontologyIDs.iterator().next().toString().contains("artifact:1:version:1")); perThreadSuccessCount.incrementAndGet(); } finally { UploadArtifactResourceImplTest.this.releaseClient(uploadArtifactClientResource); } } threadSuccessCount.incrementAndGet(); } catch (final Throwable e) { e.printStackTrace(); Assert.fail("Failed in test: " + number); } finally { closeLatch.countDown(); } } }; new Thread(runner, "TestThread" + number).start(); } // all threads are waiting on the latch. openLatch.countDown(); // release the latch // all threads are now running concurrently. closeLatch.await(50000, TimeUnit.MILLISECONDS); // closeLatch.await(); // Verify that there were no startup failures Assert.assertEquals("Some threads did not all start successfully", threadCount, threadStartCount.get()); Assert.assertEquals("Some thread loops did not start successfully", perThreadCount * threadCount, perThreadStartCount.get()); // Verify that there were no failures, as the count is only incremented // for successes, where // the closeLatch must always be called, even for failures Assert.assertEquals("Some thread loops did not complete successfully", perThreadCount * threadCount, perThreadSuccessCount.get()); Assert.assertEquals("Some threads did not complete successfully", threadCount, threadSuccessCount.get()); }
From source file:com.klinker.android.launcher.launcher3.Workspace.java
/** * Returns a new bitmap to show when the given View is being dragged around. * Responsibility for the bitmap is transferred to the caller. * @param expectedPadding padding to add to the drag view. If a different padding was used * its value will be changed// ww w . j a v a 2s . c o m */ public Bitmap createDragBitmap(View v, AtomicInteger expectedPadding) { Bitmap b; int padding = expectedPadding.get(); if (v instanceof TextView) { Drawable d = getTextViewIcon((TextView) v); Rect bounds = getDrawableBounds(d); b = Bitmap.createBitmap(bounds.width() + padding, bounds.height() + padding, Bitmap.Config.ARGB_8888); expectedPadding.set(padding - bounds.left - bounds.top); } else { b = Bitmap.createBitmap(v.getWidth() + padding, v.getHeight() + padding, Bitmap.Config.ARGB_8888); } mCanvas.setBitmap(b); drawDragView(v, mCanvas, padding); mCanvas.setBitmap(null); return b; }
From source file:com.kixeye.chassis.transport.websocket.ActionInvokingWebSocket.java
public void onWebSocketBinary(byte[] payload, int offset, int length) { try {//w ww. ja v a 2 s. co m // don't accept empty frames if (payload == null || length < 1) { throw new WebSocketServiceException(new ServiceError("EMPTY_ENVELOPE", "Empty envelope!"), "UNKNOWN", null); } // check if we need to do psk encryption byte[] processedPayload = pskFrameProcessor.processIncoming(payload, offset, length); if (processedPayload != payload) { payload = processedPayload; offset = 0; length = payload.length; } // get the envelope final WebSocketEnvelope envelope = new WebSocketEnvelope( serDe.deserialize(payload, offset, length, Envelope.class)); // gets all the actions Collection<WebSocketAction> actions = mappingRegistry.getActionMethods(envelope.getAction()); final AtomicInteger invokedActions = new AtomicInteger(0); // invokes them for (final WebSocketAction action : actions) { // get and validate type ID Class<?> messageClass = null; if (StringUtils.isNotBlank(envelope.getTypeId())) { messageClass = messageRegistry.getClassByTypeId(envelope.getTypeId()); } // validate if action has a payload class that it needs if (action.getPayloadClass() != null && messageClass == null) { throw new WebSocketServiceException(new ServiceError("INVALID_TYPE_ID", "Unknown type ID!"), envelope.getAction(), envelope.getTransactionId()); } // invoke this action if allowed if (action.canInvoke(webSocketSession, messageClass)) { invokedActions.incrementAndGet(); final Object handler = handlerCache.get(action.getHandlerClass().getName()); final Class<?> finalMessageClass = messageClass; ListenableFuture<DeferredResult<?>> invocation = serviceExecutor .submit(new Callable<DeferredResult<?>>() { @Override public DeferredResult<?> call() throws Exception { // then invoke return action.invoke( handler, new RawWebSocketMessage<>(envelope.getPayload(), finalMessageClass, messageValidator, serDe), envelope, webSocketSession); } }); Futures.addCallback(invocation, new FutureCallback<DeferredResult<?>>() { public void onSuccess(DeferredResult<?> result) { if (result != null) { result.setResultHandler(new DeferredResultHandler() { @Override public void handleResult(Object result) { if (result instanceof Exception) { onFailure((Exception) result); return; } sendResponse(result); } }); } } public void onFailure(Throwable t) { if (t instanceof InvocationTargetException) { t = ((InvocationTargetException) t).getTargetException(); } ServiceError error = ExceptionServiceErrorMapper.mapException(t); if (error != null && !ExceptionServiceErrorMapper.VALIDATION_ERROR_CODE.equals(error.code)) { logger.error("Unexpected exception throw while executing action [{}]", envelope.getAction(), t); } sendResponse(error); } public Future<Void> sendResponse(Object response) { try { return sendMessage(envelope.getAction(), envelope.getTransactionId(), response); } catch (IOException | GeneralSecurityException e) { logger.error("Unable to send message to channel", e); return Futures.immediateFuture(null); } } }, responseExecutor); } } // make sure we actually invoked something if (invokedActions.get() < 1) { throw new WebSocketServiceException( new ServiceError("INVALID_ACTION_MAPPING", "No actions invoked."), envelope.getAction(), envelope.getTransactionId()); } } catch (Exception e) { throw new RuntimeException(e); } }
From source file:com.twitter.distributedlog.BKLogHandler.java
private void asyncGetLedgerListInternal(final Comparator<LogSegmentMetadata> comparator, final LogSegmentFilter segmentFilter, final Watcher watcher, final GenericCallback<List<LogSegmentMetadata>> finalCallback, final AtomicInteger numAttemptsLeft, final AtomicLong backoffMillis) { final Stopwatch stopwatch = Stopwatch.createStarted(); try {//from w w w. j a v a 2s. c o m if (LOG.isTraceEnabled()) { LOG.trace("Async getting ledger list for {}.", getFullyQualifiedName()); } final GenericCallback<List<LogSegmentMetadata>> callback = new GenericCallback<List<LogSegmentMetadata>>() { @Override public void operationComplete(int rc, List<LogSegmentMetadata> result) { long elapsedMicros = stopwatch.stop().elapsed(TimeUnit.MICROSECONDS); if (KeeperException.Code.OK.intValue() != rc) { getListStat.registerFailedEvent(elapsedMicros); } else { if (LogSegmentFilter.DEFAULT_FILTER == segmentFilter) { isFullListFetched.set(true); } getListStat.registerSuccessfulEvent(elapsedMicros); } finalCallback.operationComplete(rc, result); } }; zooKeeperClient.get().getChildren(logMetadata.getLogSegmentsPath(), watcher, new AsyncCallback.Children2Callback() { @Override public void processResult(final int rc, final String path, final Object ctx, final List<String> children, final Stat stat) { if (KeeperException.Code.OK.intValue() != rc) { if ((KeeperException.Code.CONNECTIONLOSS.intValue() == rc || KeeperException.Code.SESSIONEXPIRED.intValue() == rc || KeeperException.Code.SESSIONMOVED.intValue() == rc) && numAttemptsLeft.decrementAndGet() > 0) { long backoffMs = backoffMillis.get(); backoffMillis.set(Math.min(conf.getZKRetryBackoffMaxMillis(), 2 * backoffMs)); scheduler.schedule(new Runnable() { @Override public void run() { asyncGetLedgerListInternal(comparator, segmentFilter, watcher, finalCallback, numAttemptsLeft, backoffMillis); } }, backoffMs, TimeUnit.MILLISECONDS); return; } callback.operationComplete(rc, null); return; } if (LOG.isTraceEnabled()) { LOG.trace("Got ledger list from {} : {}", logMetadata.getLogSegmentsPath(), children); } ledgerListWatchSet.set(true); Set<String> segmentsReceived = new HashSet<String>(); segmentsReceived.addAll(segmentFilter.filter(children)); Set<String> segmentsAdded; final Set<String> removedSegments = Collections.synchronizedSet(new HashSet<String>()); final Map<String, LogSegmentMetadata> addedSegments = Collections .synchronizedMap(new HashMap<String, LogSegmentMetadata>()); Pair<Set<String>, Set<String>> segmentChanges = logSegmentCache.diff(segmentsReceived); segmentsAdded = segmentChanges.getLeft(); removedSegments.addAll(segmentChanges.getRight()); if (segmentsAdded.isEmpty()) { if (LOG.isTraceEnabled()) { LOG.trace("No segments added for {}.", getFullyQualifiedName()); } // update the cache before fetch logSegmentCache.update(removedSegments, addedSegments); List<LogSegmentMetadata> segmentList; try { segmentList = getCachedLogSegments(comparator); } catch (UnexpectedException e) { callback.operationComplete(KeeperException.Code.DATAINCONSISTENCY.intValue(), null); return; } callback.operationComplete(KeeperException.Code.OK.intValue(), segmentList); notifyUpdatedLogSegments(segmentList); if (!removedSegments.isEmpty()) { notifyOnOperationComplete(); } return; } final AtomicInteger numChildren = new AtomicInteger(segmentsAdded.size()); final AtomicInteger numFailures = new AtomicInteger(0); for (final String segment : segmentsAdded) { metadataStore.getLogSegment(logMetadata.getLogSegmentPath(segment)) .addEventListener(new FutureEventListener<LogSegmentMetadata>() { @Override public void onSuccess(LogSegmentMetadata result) { addedSegments.put(segment, result); complete(); } @Override public void onFailure(Throwable cause) { // NONODE exception is possible in two cases // 1. A log segment was deleted by truncation between the call to getChildren and read // attempt on the znode corresponding to the segment // 2. In progress segment has been completed => inprogress ZNode does not exist if (cause instanceof KeeperException && KeeperException.Code.NONODE == ((KeeperException) cause) .code()) { removedSegments.add(segment); complete(); } else { // fail fast if (1 == numFailures.incrementAndGet()) { int rcToReturn = KeeperException.Code.SYSTEMERROR .intValue(); if (cause instanceof KeeperException) { rcToReturn = ((KeeperException) cause).code() .intValue(); } else if (cause instanceof ZKException) { rcToReturn = ((ZKException) cause) .getKeeperExceptionCode().intValue(); } // :( properly we need dlog related response code. callback.operationComplete(rcToReturn, null); return; } } } private void complete() { if (0 == numChildren.decrementAndGet() && numFailures.get() == 0) { // update the cache only when fetch completed logSegmentCache.update(removedSegments, addedSegments); List<LogSegmentMetadata> segmentList; try { segmentList = getCachedLogSegments(comparator); } catch (UnexpectedException e) { callback.operationComplete( KeeperException.Code.DATAINCONSISTENCY.intValue(), null); return; } callback.operationComplete(KeeperException.Code.OK.intValue(), segmentList); notifyUpdatedLogSegments(segmentList); notifyOnOperationComplete(); } } }); } } }, null); } catch (ZooKeeperClient.ZooKeeperConnectionException e) { getListStat.registerFailedEvent(stopwatch.stop().elapsed(TimeUnit.MICROSECONDS)); finalCallback.operationComplete(KeeperException.Code.CONNECTIONLOSS.intValue(), null); } catch (InterruptedException e) { getListStat.registerFailedEvent(stopwatch.stop().elapsed(TimeUnit.MICROSECONDS)); finalCallback.operationComplete(KeeperException.Code.CONNECTIONLOSS.intValue(), null); } }
From source file:edu.cmu.graphchi.engine.HypergraphChiEngine.java
private void execUpdates(final HypergraphChiProgram<VertexDataType, EdgeDataType> program, final ChiVertex<VertexDataType, EdgeDataType>[] vertices) { if (vertices == null || vertices.length == 0) return;/* w w w . ja va 2 s. c o m*/ TimerContext _timer = executionTimer.time(); if (Runtime.getRuntime().availableProcessors() == 1) { /* Sequential updates */ for (ChiVertex<VertexDataType, EdgeDataType> vertex : vertices) { if (vertex != null) { nupdates++; hypergraphUpdate(program, vertex, chiContext); // program.update(vertex, chiContext); } } } else { final Object termlock = new Object(); final int chunkSize = 1 + vertices.length / 64; final int nWorkers = vertices.length / chunkSize + 1; final AtomicInteger countDown = new AtomicInteger(1 + nWorkers); if (!enableDeterministicExecution) { for (ChiVertex<VertexDataType, EdgeDataType> vertex : vertices) { if (vertex != null) vertex.parallelSafe = true; } } /* Parallel updates. One thread for non-parallel safe updates, others updated in parallel. This guarantees deterministic execution. */ /* Non-safe updates */ parallelExecutor.submit(new Runnable() { public void run() { int thrupdates = 0; GraphChiContext threadContext = chiContext.clone(0); try { for (ChiVertex<VertexDataType, EdgeDataType> vertex : vertices) { if (vertex != null && !vertex.parallelSafe) { thrupdates++; hypergraphUpdate(program, vertex, threadContext); //program.update(vertex, threadContext); } } } catch (Exception e) { e.printStackTrace(); } finally { int pending = countDown.decrementAndGet(); synchronized (termlock) { nupdates += thrupdates; if (pending == 0) { termlock.notifyAll(); ; } } } } }); /* Parallel updates */ for (int thrId = 0; thrId < nWorkers; thrId++) { final int myId = thrId; final int chunkStart = myId * chunkSize; final int chunkEnd = chunkStart + chunkSize; parallelExecutor.submit(new Runnable() { public void run() { int thrupdates = 0; GraphChiContext threadContext = chiContext.clone(1 + myId); try { int end = chunkEnd; if (end > vertices.length) end = vertices.length; for (int i = chunkStart; i < end; i++) { ChiVertex<VertexDataType, EdgeDataType> vertex = vertices[i]; if (vertex != null && vertex.parallelSafe) { thrupdates++; hypergraphUpdate(program, vertex, threadContext); //program.update(vertex, threadContext); } } } catch (Exception e) { e.printStackTrace(); } finally { int pending = countDown.decrementAndGet(); synchronized (termlock) { nupdates += thrupdates; if (pending == 0) { termlock.notifyAll(); } } } } }); } synchronized (termlock) { while (countDown.get() > 0) { try { termlock.wait(1500); } catch (InterruptedException e) { // What to do? e.printStackTrace(); } if (countDown.get() > 0) logger.info("Waiting for execution to finish: countDown:" + countDown.get()); } } } _timer.stop(); }
From source file:com.sixt.service.framework.kafka.messaging.KafkaIntegrationTest.java
@Ignore("long running test") @Test// www. java 2 s . c o m public void partitionAssignmentChange() throws InterruptedException { ServiceProperties serviceProperties = new ServiceProperties(); serviceProperties.initialize(new String[] {}); // Reads environment variables set by DockerComposeHelper // Topics are created with 3 partitions - see docker-compose-integrationtest.yml Topic ping = new Topic("ping"); Topic pong = new Topic("pong"); Producer producer = new ProducerFactory(serviceProperties).createProducer(); final AtomicBoolean produceMessages = new AtomicBoolean(true); final AtomicInteger sentMessages = new AtomicInteger(0); final AtomicInteger receivedMessagesConsumer1 = new AtomicInteger(0); final CountDownLatch firstMessageProcessedConsumer1 = new CountDownLatch(1); final AtomicInteger receivedMessagesConsumer2 = new AtomicInteger(0); final CountDownLatch firstMessageProcessedConsumer2 = new CountDownLatch(1); final AtomicInteger receivedMessagesConsumer3 = new AtomicInteger(0); final CountDownLatch firstMessageProcessedConsumer3 = new CountDownLatch(1); // Produce messages until test tells producer to stop. ExecutorService producerExecutor = Executors.newSingleThreadExecutor(); producerExecutor.submit(new Runnable() { @Override public void run() { OrangeContext context = new OrangeContext(); Sleeper sleeper = new Sleeper(); try { while (produceMessages.get()) { String key = RandomStringUtils.randomAscii(5); SayHelloToCmd payload = SayHelloToCmd.newBuilder().setName(key).build(); Message request = Messages.requestFor(ping, pong, key, payload, context); producer.send(request); sentMessages.incrementAndGet(); sleeper.sleepNoException(250); } } catch (Throwable t) { logger.error("Exception in producer loop", t); } } }); // Start first producer. It should get all 3 partitions assigned. Consumer consumer1 = consumerFactoryWithHandler(serviceProperties, SayHelloToCmd.class, new MessageHandler<SayHelloToCmd>() { @Override public void onMessage(Message<SayHelloToCmd> message, OrangeContext context) { receivedMessagesConsumer1.incrementAndGet(); firstMessageProcessedConsumer1.countDown(); } }).consumerForTopic(ping, new DiscardFailedMessages()); // wait until consumer 1 is up. firstMessageProcessedConsumer1.await(); Thread.sleep(5000); // consume some messages // Now, start second processor. It should get at least one partition assigned. Consumer consumer2 = consumerFactoryWithHandler(serviceProperties, SayHelloToCmd.class, new MessageHandler<SayHelloToCmd>() { @Override public void onMessage(Message<SayHelloToCmd> message, OrangeContext context) { receivedMessagesConsumer2.incrementAndGet(); firstMessageProcessedConsumer2.countDown(); } }).consumerForTopic(ping, new DiscardFailedMessages()); // wait until the second consumer is up. firstMessageProcessedConsumer2.await(); Thread.sleep(5000); // let both consumers run a bit brutallyKillConsumer("pool-14-thread-1"); // consumer2 thread, HACKY: if this is too brittle, change the test to shutdown() //Need to wait a bit longer while Kafka "restabilizes the group" after consumer 2 was killed. // -> Consumer 1 should now get all three partitions back again. Thread.sleep(30000); // must be > than max.poll.interval.ms // Now, start third processor. It should get at least one partition assigned. Consumer consumer3 = consumerFactoryWithHandler(serviceProperties, SayHelloToCmd.class, new MessageHandler<SayHelloToCmd>() { @Override public void onMessage(Message<SayHelloToCmd> message, OrangeContext context) { receivedMessagesConsumer3.incrementAndGet(); firstMessageProcessedConsumer3.countDown(); } }).consumerForTopic(ping, new DiscardFailedMessages()); firstMessageProcessedConsumer3.await(); Thread.sleep(5000); // Now shut down the first consumer. consumer1.shutdown(); Thread.sleep(10000); // Stop the producer. produceMessages.set(false); producer.shutdown(); producerExecutor.shutdown(); Thread.sleep(3000); // give the remaining consumer the chance to consume all messages consumer3.shutdown(); // no assignment any longer // Finally, the assertions: int receivedMessagesTotal = receivedMessagesConsumer1.get() + receivedMessagesConsumer2.get() + receivedMessagesConsumer3.get(); assertEquals(sentMessages.get(), receivedMessagesTotal); assertTrue(receivedMessagesConsumer1.get() > 0); assertTrue(receivedMessagesConsumer2.get() > 0); assertTrue(receivedMessagesConsumer3.get() > 0); }
From source file:com.klinker.android.launcher.launcher3.Workspace.java
public void beginDragShared(View child, Point relativeTouchPos, DragSource source, boolean accessible) { child.clearFocus();/* w w w . j a v a2 s . c o m*/ child.setPressed(false); // The outline is used to visualize where the item will land if dropped mDragOutline = createDragOutline(child, DRAG_BITMAP_PADDING); mLauncher.onDragStarted(child); // The drag bitmap follows the touch point around on the screen AtomicInteger padding = new AtomicInteger(DRAG_BITMAP_PADDING); final Bitmap b = createDragBitmap(child, padding); final int bmpWidth = b.getWidth(); final int bmpHeight = b.getHeight(); float scale = mLauncher.getDragLayer().getLocationInDragLayer(child, mTempXY); int dragLayerX = Math.round(mTempXY[0] - (bmpWidth - scale * child.getWidth()) / 2); int dragLayerY = Math.round(mTempXY[1] - (bmpHeight - scale * bmpHeight) / 2 - padding.get() / 2); DeviceProfile grid = mLauncher.getDeviceProfile(); Point dragVisualizeOffset = null; Rect dragRect = null; if (child instanceof BubbleTextView) { BubbleTextView icon = (BubbleTextView) child; int iconSize = grid.iconSizePx; int top = child.getPaddingTop(); int left = (bmpWidth - iconSize) / 2; int right = left + iconSize; int bottom = top + iconSize; if (icon.isLayoutHorizontal()) { // If the layout is horizontal, then if we are just picking up the icon, then just // use the child position since the icon is top-left aligned. Otherwise, offset // the drag layer position horizontally so that the icon is under the current // touch position. if (icon.getIcon().getBounds().contains(relativeTouchPos.x, relativeTouchPos.y)) { dragLayerX = Math.round(mTempXY[0]); } else { dragLayerX = Math.round(mTempXY[0] + relativeTouchPos.x - (bmpWidth / 2)); } } dragLayerY += top; // Note: The drag region is used to calculate drag layer offsets, but the // dragVisualizeOffset in addition to the dragRect (the size) to position the outline. dragVisualizeOffset = new Point(-padding.get() / 2, padding.get() / 2); dragRect = new Rect(left, top, right, bottom); } else if (child instanceof FolderIcon) { int previewSize = grid.folderIconSizePx; dragRect = new Rect(0, child.getPaddingTop(), child.getWidth(), previewSize); } // Clear the pressed state if necessary if (child instanceof BubbleTextView) { BubbleTextView icon = (BubbleTextView) child; icon.clearPressedBackground(); } if (child.getTag() == null || !(child.getTag() instanceof ItemInfo)) { String msg = "Drag started with a view that has no tag set. This " + "will cause a crash (issue 11627249) down the line. " + "View: " + child + " tag: " + child.getTag(); throw new IllegalStateException(msg); } DragView dv = mDragController.startDrag(b, dragLayerX, dragLayerY, source, child.getTag(), DragController.DRAG_ACTION_MOVE, dragVisualizeOffset, dragRect, scale, accessible); dv.setIntrinsicIconScaleFactor(source.getIntrinsicIconScaleFactor()); if (child.getParent() instanceof ShortcutAndWidgetContainer) { mDragSourceInternal = (ShortcutAndWidgetContainer) child.getParent(); } b.recycle(); }
From source file:com.android.launcher3.Workspace.java
/** * Returns a new bitmap to show when the given View is being dragged around. * Responsibility for the bitmap is transferred to the caller. * @param expectedPadding padding to add to the drag view. If a different padding was used * its value will be changed//w ww . ja v a2 s . co m */ public Bitmap createDragBitmap(View v, AtomicInteger expectedPadding) { Bitmap b; int padding = expectedPadding.get(); if (v instanceof TextView) { Drawable d = ((TextView) v).getCompoundDrawables()[1]; Rect bounds = getDrawableBounds(d); b = Bitmap.createBitmap(bounds.width() + padding, bounds.height() + padding, Bitmap.Config.ARGB_8888); expectedPadding.set(padding - bounds.left - bounds.top); } else { b = Bitmap.createBitmap(v.getWidth() + padding, v.getHeight() + padding, Bitmap.Config.ARGB_8888); } mCanvas.setBitmap(b); drawDragView(v, mCanvas, padding); mCanvas.setBitmap(null); return b; }
From source file:org.apache.hadoop.hbase.client.TestFastFail.java
@Test public void testFastFail() throws IOException, InterruptedException { Admin admin = TEST_UTIL.getHBaseAdmin(); final String tableName = "testClientRelearningExperiment"; HTableDescriptor desc = new HTableDescriptor(TableName.valueOf(Bytes.toBytes(tableName))); desc.addFamily(new HColumnDescriptor(FAMILY)); admin.createTable(desc, Bytes.toBytes("aaaa"), Bytes.toBytes("zzzz"), 32); final long numRows = 1000; Configuration conf = TEST_UTIL.getConfiguration(); conf.setLong(HConstants.HBASE_CLIENT_OPERATION_TIMEOUT, SLEEPTIME * 100); conf.setInt(HConstants.HBASE_CLIENT_PAUSE, SLEEPTIME / 10); conf.setBoolean(HConstants.HBASE_CLIENT_FAST_FAIL_MODE_ENABLED, true); conf.setLong(HConstants.HBASE_CLIENT_FAST_FAIL_THREASHOLD_MS, 0); conf.setClass(HConstants.HBASE_CLIENT_FAST_FAIL_INTERCEPTOR_IMPL, MyPreemptiveFastFailInterceptor.class, PreemptiveFastFailInterceptor.class); final Connection connection = ConnectionFactory.createConnection(conf); /**//from w w w . j a v a 2 s. co m * Write numRows worth of data, so that the workers can arbitrarily read. */ List<Put> puts = new ArrayList<>(); for (long i = 0; i < numRows; i++) { byte[] rowKey = longToByteArrayKey(i); Put put = new Put(rowKey); byte[] value = rowKey; // value is the same as the row key put.add(FAMILY, QUALIFIER, value); puts.add(put); } try (Table table = connection.getTable(TableName.valueOf(tableName))) { table.put(puts); LOG.info("Written all puts."); } /** * The number of threads that are going to perform actions against the test * table. */ int nThreads = 100; ExecutorService service = Executors.newFixedThreadPool(nThreads); final CountDownLatch continueOtherHalf = new CountDownLatch(1); final CountDownLatch doneHalfway = new CountDownLatch(nThreads); final AtomicInteger numSuccessfullThreads = new AtomicInteger(0); final AtomicInteger numFailedThreads = new AtomicInteger(0); // The total time taken for the threads to perform the second put; final AtomicLong totalTimeTaken = new AtomicLong(0); final AtomicInteger numBlockedWorkers = new AtomicInteger(0); final AtomicInteger numPreemptiveFastFailExceptions = new AtomicInteger(0); List<Future<Boolean>> futures = new ArrayList<Future<Boolean>>(); for (int i = 0; i < nThreads; i++) { futures.add(service.submit(new Callable<Boolean>() { /** * The workers are going to perform a couple of reads. The second read * will follow the killing of a regionserver so that we make sure that * some of threads go into PreemptiveFastFailExcception */ public Boolean call() throws Exception { try (Table table = connection.getTable(TableName.valueOf(tableName))) { Thread.sleep(Math.abs(random.nextInt()) % 250); // Add some jitter here byte[] row = longToByteArrayKey(Math.abs(random.nextLong()) % numRows); Get g = new Get(row); g.addColumn(FAMILY, QUALIFIER); try { table.get(g); } catch (Exception e) { LOG.debug("Get failed : ", e); doneHalfway.countDown(); return false; } // Done with one get, proceeding to do the next one. doneHalfway.countDown(); continueOtherHalf.await(); long startTime = System.currentTimeMillis(); g = new Get(row); g.addColumn(FAMILY, QUALIFIER); try { table.get(g); // The get was successful numSuccessfullThreads.addAndGet(1); } catch (Exception e) { if (e instanceof PreemptiveFastFailException) { // We were issued a PreemptiveFastFailException numPreemptiveFastFailExceptions.addAndGet(1); } // Irrespective of PFFE, the request failed. numFailedThreads.addAndGet(1); return false; } finally { long enTime = System.currentTimeMillis(); totalTimeTaken.addAndGet(enTime - startTime); if ((enTime - startTime) >= SLEEPTIME) { // Considering the slow workers as the blockedWorkers. // This assumes that the threads go full throttle at performing // actions. In case the thread scheduling itself is as slow as // SLEEPTIME, then this test might fail and so, we might have // set it to a higher number on slower machines. numBlockedWorkers.addAndGet(1); } } return true; } catch (Exception e) { LOG.error("Caught unknown exception", e); doneHalfway.countDown(); return false; } } })); } doneHalfway.await(); ClusterStatus status = TEST_UTIL.getHBaseCluster().getClusterStatus(); // Kill a regionserver TEST_UTIL.getHBaseCluster().getRegionServer(0).getRpcServer().stop(); TEST_UTIL.getHBaseCluster().getRegionServer(0).stop("Testing"); // Let the threads continue going continueOtherHalf.countDown(); Thread.sleep(2 * SLEEPTIME); // Restore the cluster TEST_UTIL.getHBaseCluster().restoreClusterStatus(status); int numThreadsReturnedFalse = 0; int numThreadsReturnedTrue = 0; int numThreadsThrewExceptions = 0; for (Future<Boolean> f : futures) { try { numThreadsReturnedTrue += f.get() ? 1 : 0; numThreadsReturnedFalse += f.get() ? 0 : 1; } catch (Exception e) { numThreadsThrewExceptions++; } } LOG.debug("numThreadsReturnedFalse:" + numThreadsReturnedFalse + " numThreadsReturnedTrue:" + numThreadsReturnedTrue + " numThreadsThrewExceptions:" + numThreadsThrewExceptions + " numFailedThreads:" + numFailedThreads.get() + " numSuccessfullThreads:" + numSuccessfullThreads.get() + " numBlockedWorkers:" + numBlockedWorkers.get() + " totalTimeWaited: " + totalTimeTaken.get() / (numBlockedWorkers.get() == 0 ? Long.MAX_VALUE : numBlockedWorkers.get()) + " numPFFEs: " + numPreemptiveFastFailExceptions.get()); assertEquals( "The expected number of all the successfull and the failed " + "threads should equal the total number of threads that we spawned", nThreads, numFailedThreads.get() + numSuccessfullThreads.get()); assertEquals("All the failures should be coming from the secondput failure", numFailedThreads.get(), numThreadsReturnedFalse); assertEquals("Number of threads that threw execution exceptions " + "otherwise should be 0", numThreadsThrewExceptions, 0); assertEquals("The regionservers that returned true should equal to the" + " number of successful threads", numThreadsReturnedTrue, numSuccessfullThreads.get()); /* 'should' is not worthy of an assert. Disabling because randomly this seems to randomly * not but true. St.Ack 20151012 * assertTrue( "There should be atleast one thread that retried instead of failing", MyPreemptiveFastFailInterceptor.numBraveSouls.get() > 0); assertTrue( "There should be atleast one PreemptiveFastFail exception," + " otherwise, the test makes little sense." + "numPreemptiveFastFailExceptions: " + numPreemptiveFastFailExceptions.get(), numPreemptiveFastFailExceptions.get() > 0); */ assertTrue( "Only few thread should ideally be waiting for the dead " + "regionserver to be coming back. numBlockedWorkers:" + numBlockedWorkers.get() + " threads that retried : " + MyPreemptiveFastFailInterceptor.numBraveSouls.get(), numBlockedWorkers.get() <= MyPreemptiveFastFailInterceptor.numBraveSouls.get()); }
From source file:com.zyk.launcher.Workspace.java
public void beginDragShared(View child, DragSource source) { // mLauncher.setDragController(true); ////www .jav a2 s . c om child.clearFocus(); //??false?false? child.setPressed(false); //??????? // The outline is used to visualize where the item will land if dropped mDragOutline = createDragOutline(child, DRAG_BITMAP_PADDING); mLauncher.onDragStarted(child); // The drag bitmap follows the touch point around on the screen AtomicInteger padding = new AtomicInteger(DRAG_BITMAP_PADDING); final Bitmap b = Utils.createDragBitmap(child, padding); final int bmpWidth = b.getWidth(); final int bmpHeight = b.getHeight(); float scale = mLauncher.getDragLayer().getLocationInDragLayer(child, mTempXY); int dragLayerX = Math.round(mTempXY[0] - (bmpWidth - scale * child.getWidth()) / 2); int dragLayerY = Math.round(mTempXY[1] - (bmpHeight - scale * bmpHeight) / 2 - padding.get() / 2); LauncherAppState app = LauncherAppState.getInstance(); DeviceProfile grid = app.getDynamicGrid().getDeviceProfile(); Point dragVisualizeOffset = null; Rect dragRect = null; if (child instanceof BubbleTextView) { int iconSize = grid.iconSizePx; int top = child.getPaddingTop(); int left = (bmpWidth - iconSize) / 2; int right = left + iconSize; int bottom = top + iconSize; dragLayerY += top; // Note: The drag region is used to calculate drag layer offsets, but the // dragVisualizeOffset in addition to the dragRect (the size) to position the outline. dragVisualizeOffset = new Point(-padding.get() / 2, padding.get() / 2); dragRect = new Rect(left, top, right, bottom); } else if (child instanceof FolderIcon) { int previewSize = grid.folderIconSizePx; dragRect = new Rect(0, child.getPaddingTop(), child.getWidth(), previewSize); } // Clear the pressed state if necessary if (child instanceof BubbleTextView) { BubbleTextView icon = (BubbleTextView) child; icon.clearPressedBackground(); } if (child.getTag() == null || !(child.getTag() instanceof ItemInfo)) { String msg = "Drag started with a view that has no tag set. This " + "will cause a crash (issue 11627249) down the line. " + "View: " + child + " tag: " + child.getTag(); throw new IllegalStateException(msg); } DragView dv = mDragController.startDrag(b, dragLayerX, dragLayerY, source, child.getTag(), DragController.DRAG_ACTION_MOVE, dragVisualizeOffset, dragRect, scale); dv.setIntrinsicIconScaleFactor(source.getIntrinsicIconScaleFactor()); if (child.getParent() instanceof ShortcutAndWidgetContainer) { mDragSourceInternal = (ShortcutAndWidgetContainer) child.getParent(); } b.recycle(); }