Java Code Examples for java.util.concurrent.atomic.AtomicReference

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project flume_1, under directory /flume-core/src/test/java/com/cloudera/flume/collector/.

Source file: TestCollectorSink.java

  16 
vote

/** 
 * This tests close() and interrupt on a collectorSink in such a way that close always happens after open has completed.
 */
@Test public void testHdfsDownInterruptAfterOpen() throws FlumeSpecException, IOException, InterruptedException {
  final EventSink snk=FlumeBuilder.buildSink(new Context(),"collectorSink(\"hdfs://nonexistant/user/foo\", \"foo\")");
  final CountDownLatch started=new CountDownLatch(1);
  final CountDownLatch done=new CountDownLatch(1);
  final AtomicReference<Exception> are=new AtomicReference(null);
  Thread t=new Thread("append thread"){
    public void run(){
      Event e=new EventImpl("foo".getBytes());
      try {
        snk.open();
        started.countDown();
        snk.append(e);
      }
 catch (      Exception e1) {
        LOG.info("don't care about this exception: ",e1);
        are.set(e1);
      }
      done.countDown();
    }
  }
;
  t.start();
  boolean begun=started.await(60,TimeUnit.SECONDS);
  assertTrue("took too long to start",begun);
  snk.close();
  LOG.info("Interrupting appending thread");
  t.interrupt();
  boolean completed=done.await(60,TimeUnit.SECONDS);
  assertTrue("Timed out when attempting to shutdown",completed);
}
 

Example 2

From project agit, under directory /agit/src/main/java/com/madgag/agit/filepath/.

Source file: FilterableFileListAdapter.java

  15 
vote

public FilterableFileListAdapter(final List<FilePath> items,Context context,AtomicReference<FilePathMatcher> visibleFilePathMatcher){
  super(items,viewInflatorFor(context,file_list_item),reflectiveFactoryFor(FileViewHolder.class,visibleFilePathMatcher));
  this.items=items;
  this.visibleFilePathMatcher=visibleFilePathMatcher;
  cachingFilePathListMatcher=new CachingFilePathListMatcher(this.items);
}
 

Example 3

From project Agot-Java, under directory /src/main/java/got/ui/update/.

Source file: Util.java

  15 
vote

public static <T>T runInSwingEventThread(final Task<T> task){
  if (SwingUtilities.isEventDispatchThread()) {
    return task.run();
  }
  final AtomicReference<T> results=new AtomicReference<T>();
  try {
    SwingUtilities.invokeAndWait(new Runnable(){
      public void run(){
        results.set(task.run());
      }
    }
);
  }
 catch (  final InterruptedException e) {
    throw new IllegalStateException(e);
  }
catch (  final InvocationTargetException e) {
    throw new IllegalStateException(e);
  }
  return results.get();
}
 

Example 4

From project airlift, under directory /dbpool/src/test/java/io/airlift/dbpool/.

Source file: ManagedDataSourceTest.java

  15 
vote

@Test public void testAcquirePermitInterrupted() throws Exception {
  final ManagedDataSource dataSource=new MockManagedDataSource(1,new Duration(5000,MILLISECONDS));
  assertEquals(dataSource.getMaxConnectionWaitMillis(),5000);
  Connection connection=dataSource.getConnection();
  assertEquals(dataSource.getConnectionsActive(),1);
  final CountDownLatch startLatch=new CountDownLatch(1);
  final CountDownLatch endLatch=new CountDownLatch(1);
  final AtomicBoolean wasInterrupted=new AtomicBoolean();
  final AtomicReference<SQLException> exception=new AtomicReference<SQLException>();
  Thread createThread=new Thread(){
    @Override public void run(){
      startLatch.countDown();
      try {
        dataSource.getConnection();
      }
 catch (      SQLException e) {
        exception.set(e);
      }
 finally {
        wasInterrupted.set(isInterrupted());
        endLatch.countDown();
      }
    }
  }
;
  createThread.start();
  startLatch.await();
  createThread.interrupt();
  endLatch.await();
  assertTrue(wasInterrupted.get(),"createThread.isInterrupted()");
  SQLException sqlException=exception.get();
  assertNotNull(sqlException);
  assertInstanceOf(sqlException.getCause(),InterruptedException.class);
  connection.close();
  assertEquals(dataSource.getConnectionsActive(),0);
}
 

Example 5

From project Android, under directory /app/src/main/java/com/github/mobile/util/.

Source file: AvatarLoader.java

  15 
vote

/** 
 * Sets the logo on the  {@link ActionBar} to the user's avatar.
 * @param actionBar
 * @param userReference
 * @return this helper
 */
public AvatarLoader bind(final ActionBar actionBar,final AtomicReference<User> userReference){
  if (userReference == null)   return this;
  final User user=userReference.get();
  final String userId=getId(user);
  if (userId == null)   return this;
  final String avatarUrl=user.getAvatarUrl();
  if (TextUtils.isEmpty(avatarUrl))   return this;
  BitmapDrawable loadedImage=loaded.get(userId);
  if (loadedImage != null) {
    actionBar.setLogo(loadedImage);
    return this;
  }
  new FetchAvatarTask(context){
    @Override public BitmapDrawable call() throws Exception {
      final BitmapDrawable image=getImage(userId);
      if (image != null)       return image;
 else       return fetchAvatar(avatarUrl,userId);
    }
    @Override protected void onSuccess(    BitmapDrawable image) throws Exception {
      if (userId.equals(getId(userReference.get())))       actionBar.setLogo(image);
    }
  }
.execute();
  return this;
}
 

Example 6

From project AndroidLab, under directory /libs/unboundid/docs/examples/.

Source file: AuthRateThread.java

  15 
vote

/** 
 * Creates a new auth rate thread with the provided information.
 * @param threadNumber      The thread number for this thread.
 * @param searchConnection  The connection to use for the searches.
 * @param bindConnection    The connection to use for the  binds.
 * @param baseDN            The value pattern to use for the base DNs.
 * @param scope             The scope to use for the searches.
 * @param filter            The value pattern for the filters.
 * @param attributes        The set of attributes to return.
 * @param userPassword      The password to use for the bind operations.
 * @param authType          The type of authentication to perform.
 * @param startBarrier      A barrier used to coordinate starting between allof the threads.
 * @param authCounter       A value that will be used to keep track of thetotal number of authentications performed.
 * @param authDurations     A value that will be used to keep track of thetotal duration for all authentications.
 * @param errorCounter      A value that will be used to keep track of thenumber of errors encountered while searching.
 * @param rcCounter         The result code counter to use for keeping trackof the result codes for failed operations.
 * @param rateBarrier       The barrier to use for controlling the rate ofauthorizations.   {@code null} if no rate-limitingshould be used.
 */
AuthRateThread(final int threadNumber,final LDAPConnection searchConnection,final LDAPConnection bindConnection,final ValuePattern baseDN,final SearchScope scope,final ValuePattern filter,final String[] attributes,final String userPassword,final String authType,final CyclicBarrier startBarrier,final AtomicLong authCounter,final AtomicLong authDurations,final AtomicLong errorCounter,final ResultCodeCounter rcCounter,final FixedRateBarrier rateBarrier){
  setName("AuthRate Thread " + threadNumber);
  setDaemon(true);
  this.searchConnection=searchConnection;
  this.bindConnection=bindConnection;
  this.baseDN=baseDN;
  this.filter=filter;
  this.userPassword=userPassword;
  this.authCounter=authCounter;
  this.authDurations=authDurations;
  this.errorCounter=errorCounter;
  this.rcCounter=rcCounter;
  this.startBarrier=startBarrier;
  fixedRateBarrier=rateBarrier;
  searchConnection.setConnectionName("search-" + threadNumber);
  bindConnection.setConnectionName("bind-" + threadNumber);
  if (authType.equalsIgnoreCase("cram-md5")) {
    this.authType=AUTH_TYPE_CRAM_MD5;
  }
 else   if (authType.equalsIgnoreCase("digest-md5")) {
    this.authType=AUTH_TYPE_DIGEST_MD5;
  }
 else   if (authType.equalsIgnoreCase("plain")) {
    this.authType=AUTH_TYPE_PLAIN;
  }
 else {
    this.authType=AUTH_TYPE_SIMPLE;
  }
  resultCode=new AtomicReference<ResultCode>(null);
  authThread=new AtomicReference<Thread>(null);
  stopRequested=new AtomicBoolean(false);
  searchRequest=new SearchRequest("",scope,Filter.createPresenceFilter("objectClass"),attributes);
}
 

Example 7

From project android_packages_apps_Gallery3D, under directory /src/com/cooliris/cache/.

Source file: CacheService.java

  15 
vote

private static final void restartThread(final AtomicReference<Thread> threadRef,final String name,final Runnable action){
  final Thread newThread=new Thread(){
    public void run(){
      try {
        action.run();
      }
  finally {
        threadRef.compareAndSet(this,null);
      }
    }
  }
;
  newThread.setName(name);
  newThread.start();
  final Thread existingThread=threadRef.getAndSet(newThread);
  if (existingThread != null) {
    existingThread.interrupt();
  }
}
 

Example 8

From project android_packages_apps_Nfc, under directory /src/com/android/nfc/.

Source file: RegisteredComponentCache.java

  15 
vote

public RegisteredComponentCache(Context context,String action,String metaDataName){
  mContext=context;
  mAction=action;
  mMetaDataName=metaDataName;
  generateComponentsList();
  final BroadcastReceiver receiver=new BroadcastReceiver(){
    @Override public void onReceive(    Context context1,    Intent intent){
      generateComponentsList();
    }
  }
;
  mReceiver=new AtomicReference<BroadcastReceiver>(receiver);
  IntentFilter intentFilter=new IntentFilter();
  intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
  intentFilter.addAction(Intent.ACTION_PACKAGE_CHANGED);
  intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
  intentFilter.addDataScheme("package");
  mContext.registerReceiver(receiver,intentFilter);
  IntentFilter sdFilter=new IntentFilter();
  sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE);
  sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
  mContext.registerReceiver(receiver,sdFilter);
}
 

Example 9

From project archaius, under directory /archaius-core/src/test/java/com/netflix/config/.

Source file: ConcurrentMapConfigurationTest.java

  15 
vote

@Test public void testListeners(){
  ConcurrentMapConfiguration conf=new ConcurrentMapConfiguration();
  final AtomicReference<ConfigurationEvent> eventRef=new AtomicReference<ConfigurationEvent>();
  conf.addConfigurationListener(new ConfigurationListener(){
    @Override public void configurationChanged(    ConfigurationEvent arg0){
      eventRef.set(arg0);
    }
  }
);
  conf.addProperty("key","1");
  assertEquals(1,conf.getInt("key"));
  ConfigurationEvent event=eventRef.get();
  assertEquals("key",event.getPropertyName());
  assertEquals("1",event.getPropertyValue());
  assertTrue(conf == event.getSource());
  assertEquals(AbstractConfiguration.EVENT_ADD_PROPERTY,event.getType());
  conf.setProperty("key","2");
  event=eventRef.get();
  assertEquals("key",event.getPropertyName());
  assertEquals("2",event.getPropertyValue());
  assertTrue(conf == event.getSource());
  assertEquals(AbstractConfiguration.EVENT_SET_PROPERTY,event.getType());
  conf.clearProperty("key");
  event=eventRef.get();
  assertEquals("key",event.getPropertyName());
  assertNull(event.getPropertyValue());
  assertTrue(conf == event.getSource());
  assertEquals(AbstractConfiguration.EVENT_CLEAR_PROPERTY,event.getType());
  conf.clear();
  assertFalse(conf.getKeys().hasNext());
  event=eventRef.get();
  assertTrue(conf == event.getSource());
  assertEquals(AbstractConfiguration.EVENT_CLEAR,event.getType());
}
 

Example 10

From project ardverk-commons, under directory /src/main/java/org/ardverk/io/.

Source file: IoUtils.java

  15 
vote

/** 
 * Closes the given  {@code Object}. Returns  {@code true} on successand  {@code false} on failure. All {@link IOException}s will be caught and no error will be thrown if the Object isn't any of the supported types.
 * @see Closeable
 * @see #close(Closeable)
 * @see AutoCloseable
 * @see #close(AutoCloseable)
 * @see Socket
 * @see #close(Socket)
 * @see ServerSocket
 * @see #close(ServerSocket)
 * @see DatagramSocket
 * @see #close(DatagramSocket)
 * @see AtomicReference
 * @see #close(AtomicReference)
 */
public static boolean close(Object o){
  if (o instanceof Closeable) {
    return close((Closeable)o);
  }
 else   if (o instanceof AutoCloseable) {
    return close((AutoCloseable)o);
  }
 else   if (o instanceof Socket) {
    return close((Socket)o);
  }
 else   if (o instanceof ServerSocket) {
    return close((ServerSocket)o);
  }
 else   if (o instanceof DatagramSocket) {
    return close((DatagramSocket)o);
  }
 else   if (o instanceof AtomicReference<?>) {
    return close(((AtomicReference<?>)o));
  }
  return false;
}
 

Example 11

From project Arecibo, under directory /collector/src/main/java/com/ning/arecibo/collector/resources/.

Source file: HostDataResource.java

  15 
vote

private void writeJsonForStoredChunks(final JsonGenerator generator,final ObjectWriter writer,final Map<Integer,Map<Integer,DecimatingSampleFilter>> filters,final List<Integer> hostIdsList,final List<Integer> sampleKindIdsList,final DateTime startTime,final DateTime endTime,final boolean decodeSamples) throws IOException, ExecutionException {
  final AtomicReference<Integer> lastHostId=new AtomicReference<Integer>(null);
  final AtomicReference<Integer> lastSampleKindId=new AtomicReference<Integer>(null);
  final List<TimelineChunk> chunksForHostAndSampleKind=new ArrayList<TimelineChunk>();
  dao.getSamplesByHostIdsAndSampleKindIds(hostIdsList,sampleKindIdsList,startTime,endTime,new TimelineChunkConsumer(){
    @Override public void processTimelineChunk(    final TimelineChunk chunks){
      final Integer previousHostId=lastHostId.get();
      final Integer previousSampleKindId=lastSampleKindId.get();
      final Integer currentHostId=chunks.getHostId();
      final Integer currentSampleKindId=chunks.getSampleKindId();
      chunksForHostAndSampleKind.add(chunks);
      if (previousHostId != null && (!previousHostId.equals(currentHostId) || !previousSampleKindId.equals(currentSampleKindId))) {
        try {
          writeJsonForChunks(generator,writer,filters,chunksForHostAndSampleKind,decodeSamples);
        }
 catch (        RuntimeException e) {
          throw new WebApplicationException(e,buildServiceUnavailableResponse());
        }
catch (        IOException e) {
          throw new WebApplicationException(e,buildServiceUnavailableResponse());
        }
catch (        ExecutionException e) {
          throw new WebApplicationException(e,buildServiceUnavailableResponse());
        }
        chunksForHostAndSampleKind.clear();
      }
      lastHostId.set(currentHostId);
      lastSampleKindId.set(currentSampleKindId);
    }
  }
);
  if (chunksForHostAndSampleKind.size() > 0) {
    writeJsonForChunks(generator,writer,filters,chunksForHostAndSampleKind,decodeSamples);
    chunksForHostAndSampleKind.clear();
  }
}
 

Example 12

From project avro, under directory /lang/java/ipc/src/test/java/org/apache/avro/ipc/.

Source file: TestNettyServerWithCallbacks.java

  15 
vote

@Test() public void error() throws IOException, InterruptedException, TimeoutException {
  try {
    simpleClient.error();
    Assert.fail("Expected " + TestError.class.getCanonicalName());
  }
 catch (  TestError e) {
  }
catch (  AvroRemoteException e) {
    e.printStackTrace();
    Assert.fail("Unexpected error: " + e.toString());
  }
  CallFuture<Void> future=new CallFuture<Void>();
  simpleClient.error(future);
  try {
    future.get(2,TimeUnit.SECONDS);
    Assert.fail("Expected " + TestError.class.getCanonicalName() + " to be thrown");
  }
 catch (  ExecutionException e) {
    Assert.assertTrue("Expected " + TestError.class.getCanonicalName(),e.getCause() instanceof TestError);
  }
  Assert.assertNotNull(future.getError());
  Assert.assertTrue("Expected " + TestError.class.getCanonicalName(),future.getError() instanceof TestError);
  Assert.assertNull(future.getResult());
  final CountDownLatch latch=new CountDownLatch(1);
  final AtomicReference<Throwable> errorRef=new AtomicReference<Throwable>();
  simpleClient.error(new Callback<Void>(){
    @Override public void handleResult(    Void result){
      Assert.fail("Expected " + TestError.class.getCanonicalName());
    }
    @Override public void handleError(    Throwable error){
      errorRef.set(error);
      latch.countDown();
    }
  }
);
  Assert.assertTrue("Timed out waiting for error",latch.await(2,TimeUnit.SECONDS));
  Assert.assertNotNull(errorRef.get());
  Assert.assertTrue(errorRef.get() instanceof TestError);
}
 

Example 13

From project awaitility, under directory /awaitility/src/main/java/com/jayway/awaitility/core/.

Source file: ConditionFactory.java

  15 
vote

/** 
 * Await until a Atomic variable has a value matching the specified {@link Matcher}. E.g. <pre> await().untilAtomic(myAtomic, is(greaterThan(2))); </pre>
 * @param number the atomic variable
 * @param matcher the matcher The hamcrest matcher that checks whether the condition is fulfilled.
 * @throws Exception the exception
 */
public <V>void untilAtomic(final AtomicReference<V> atomic,final Matcher<? super V> matcher) throws Exception {
  until(new CallableHamcrestCondition<V>(new Callable<V>(){
    public V call() throws Exception {
      return atomic.get();
    }
  }
,matcher,generateConditionSettings()));
}
 

Example 14

From project azkaban, under directory /azkaban/src/java/azkaban/flow/.

Source file: RefreshableFlowManager.java

  15 
vote

public RefreshableFlowManager(JobManager jobManager,FlowExecutionSerializer serializer,FlowExecutionDeserializer deserializer,File storageDirectory,long lastId){
  this.jobManager=jobManager;
  this.serializer=serializer;
  this.deserializer=deserializer;
  this.storageDirectory=storageDirectory;
  this.delegateManager=new AtomicReference<ImmutableFlowManager>(null);
  reloadInternal(lastId);
}
 

Example 15

From project beam-meris-icol, under directory /src/main/java/org/esa/beam/meris/icol/common/.

Source file: CloudDistanceOp.java

  15 
vote

private PixelPos findFirstCloudPix(final PixelPos startPixel,final PixelPos endPixel,final Tile cloudFlags){
  ShapeRasterizer.LineRasterizer lineRasterizer=new ShapeRasterizer.BresenhamLineRasterizer();
  final AtomicReference<PixelPos> result=new AtomicReference<PixelPos>();
  final Rectangle isCloudRect=cloudFlags.getRectangle();
  ShapeRasterizer.LinePixelVisitor visitor=new ShapeRasterizer.LinePixelVisitor(){
    @Override public void visit(    int x,    int y){
      if (result.get() == null && isCloudRect.contains(x,y) && cloudFlags.getSampleBit(x,y,CloudClassificationOp.F_CLOUD)) {
        result.set(new PixelPos(x,y));
      }
    }
  }
;
  lineRasterizer.rasterize(MathUtils.floorInt(startPixel.x),MathUtils.floorInt(startPixel.y),MathUtils.floorInt(endPixel.x),MathUtils.floorInt(endPixel.y),visitor);
  return result.get();
}
 

Example 16

From project big-data-plugin, under directory /shims/common/test-src/org/pentaho/hadoop/shim/common/mapred/.

Source file: TaskCompletionEventProxyTest.java

  15 
vote

@Test public void getTaskStatus(){
  final AtomicReference<org.apache.hadoop.mapred.TaskCompletionEvent.Status> status=new AtomicReference<org.apache.hadoop.mapred.TaskCompletionEvent.Status>();
  org.apache.hadoop.mapred.TaskCompletionEvent delegate=new org.apache.hadoop.mapred.TaskCompletionEvent(){
    public Status getTaskStatus(){
      return status.get();
    }
  }
;
  TaskCompletionEventProxy proxy=new TaskCompletionEventProxy(delegate);
  status.set(org.apache.hadoop.mapred.TaskCompletionEvent.Status.FAILED);
  assertEquals(TaskCompletionEvent.Status.FAILED,proxy.getTaskStatus());
  status.set(org.apache.hadoop.mapred.TaskCompletionEvent.Status.KILLED);
  assertEquals(TaskCompletionEvent.Status.KILLED,proxy.getTaskStatus());
  status.set(org.apache.hadoop.mapred.TaskCompletionEvent.Status.OBSOLETE);
  assertEquals(TaskCompletionEvent.Status.OBSOLETE,proxy.getTaskStatus());
  status.set(org.apache.hadoop.mapred.TaskCompletionEvent.Status.SUCCEEDED);
  assertEquals(TaskCompletionEvent.Status.SUCCEEDED,proxy.getTaskStatus());
  status.set(org.apache.hadoop.mapred.TaskCompletionEvent.Status.TIPFAILED);
  assertEquals(TaskCompletionEvent.Status.TIPFAILED,proxy.getTaskStatus());
}
 

Example 17

From project camelpe, under directory /examples/loan-broker-common/src/test/java/net/camelpe/examples/loanbroker/queue/.

Source file: LoanBrokerQueueInContainerTest.java

  15 
vote

@Test public void assertThatLoanBrokerProcessesLoanRequest() throws Exception {
  final String ssn="Client-A";
  final String loanRequest="Request quote for lowest rate of lending bank";
  final CountDownLatch loanReplyReceived=new CountDownLatch(1);
  final AtomicReference<Message> receivedLoanReply=new AtomicReference<Message>();
  final MessageListener loanReplyListenerDelegate=new MessageListener(){
    @Override public void onMessage(    final Message arg0){
      receivedLoanReply.set(arg0);
      loanReplyReceived.countDown();
    }
  }
;
  final LoanReplyListener loanReplyListener=new LoanReplyListener(jmsServer,loanReplyListenerDelegate);
  loanReplyListener.start();
  final LoanRequestSender loanRequestSender=new LoanRequestSender(jmsServer);
  loanRequestSender.start();
  loanRequestSender.requestLoan(ssn,loanRequest);
  loanRequestSender.stop();
  loanReplyReceived.await();
  loanReplyListener.stop();
}
 

Example 18

From project clj-ds, under directory /src/main/java/com/trifork/clj_ds/.

Source file: PersistentHashMap.java

  15 
vote

TransientHashMap(AtomicReference<Thread> edit,INode root,int count,boolean hasNull,V nullValue){
  this.edit=edit;
  this.root=root;
  this.count=count;
  this.hasNull=hasNull;
  this.nullValue=nullValue;
}
 

Example 19

From project clojure, under directory /src/jvm/clojure/lang/.

Source file: PersistentHashMap.java

  15 
vote

TransientHashMap(AtomicReference<Thread> edit,INode root,int count,boolean hasNull,Object nullValue){
  this.edit=edit;
  this.root=root;
  this.count=count;
  this.hasNull=hasNull;
  this.nullValue=nullValue;
}
 

Example 20

From project cloudhopper-commons-util, under directory /src/main/java/com/cloudhopper/commons/util/windowing/.

Source file: DefaultWindowFuture.java

  15 
vote

/** 
 * Creates a new DefaultWindowFuture.
 * @param window The window that created this future.  Saved as a weakreference to prevent circular references.
 * @param windowLock The shared lock from the window
 * @param completedCondition The shared condition to wait on
 * @param key The key of the future
 * @param request The request of the future
 * @param callerStateHint The initial state of the caller hint
 * @param originalOfferTimeoutMillis
 * @param windowSize Size of the window after this request was added. Usefulfor calculating an estimated response time for this request rather than all requests ahead of it in the window.
 * @param offerTimestamp The timestamp when the request was offered
 * @param acceptTimestamp The timestamp when the request was accepted
 * @param expireTimestamp The timestamp when the request will expire or -1if no expiration is set
 */
protected DefaultWindowFuture(Window window,ReentrantLock windowLock,Condition completedCondition,K key,R request,int callerStateHint,long originalOfferTimeoutMillis,int windowSize,long offerTimestamp,long acceptTimestamp,long expireTimestamp){
  this.window=new WeakReference<Window>(window);
  this.windowLock=windowLock;
  this.completedCondition=completedCondition;
  this.key=key;
  this.request=request;
  this.response=new AtomicReference<P>();
  this.cause=new AtomicReference<Throwable>();
  this.callerStateHint=new AtomicInteger(callerStateHint);
  this.done=new AtomicBoolean(false);
  this.originalOfferTimeoutMillis=originalOfferTimeoutMillis;
  this.windowSize=windowSize;
  this.offerTimestamp=offerTimestamp;
  this.acceptTimestamp=acceptTimestamp;
  this.expireTimestamp=expireTimestamp;
  this.doneTimestamp=new AtomicLong(0);
}
 

Example 21

From project CMake-runner-plugin, under directory /cmake-runner-test/src/jetbrains/buildServer/cmakerunner/tests/agent/output/.

Source file: OutputListenerTest.java

  15 
vote

@Test public void testTargetsFolding() throws Exception {
  final BracketSequenceMakeLogger logger=new BracketSequenceMakeLogger();
  final AtomicReference<List<String>> makeTasks=new AtomicReference<List<String>>(Arrays.asList("all","clean"));
  final MakeOutputListener mll=new MakeOutputListener(logger,makeTasks);
{
    final File workingDirectory=new File("");
    final String wdAp=workingDirectory.getAbsolutePath();
    mll.processStarted("make",workingDirectory);
    mll.onStandardOutput(generateEnterMessage(wdAp,-1));
    mll.onStandardOutput(generateEnterMessage(wdAp + "/b",1));
    mll.onStandardOutput(generateLeaveMessage(wdAp + "/b",1));
    mll.onStandardOutput(generateEnterMessage(wdAp + "/c",1));
    mll.onStandardOutput(generateLeaveMessage(wdAp + "/c",1));
    mll.onStandardOutput(generateEnterMessage(wdAp + "/a",1));
    mll.onStandardOutput(generateEnterMessage(wdAp + "/a/d",2));
    mll.onStandardOutput(generateLeaveMessage(wdAp + "/a/d",2));
    mll.onStandardOutput(generateLeaveMessage(wdAp + "/a",1));
    mll.onStandardOutput(generateEnterMessage(wdAp,1));
    mll.onStandardOutput(generateLeaveMessage(wdAp,1));
    mll.onStandardOutput(generateEnterMessage(wdAp + "/c",1));
    mll.onStandardOutput(generateLeaveMessage(wdAp + "/c",1));
    mll.onStandardOutput(generateEnterMessage(wdAp,1));
    mll.onStandardOutput(generateLeaveMessage(wdAp,1));
    mll.onStandardOutput(generateLeaveMessage(wdAp,-1));
    mll.processFinished(0);
  }
  Assert.assertTrue(logger.isSequenceCorrect());
  Assert.assertEquals(logger.getSequence(),"(()()(()))(())");
}
 

Example 22

From project cometd, under directory /cometd-java/cometd-java-annotations/src/test/java/org/cometd/annotation/.

Source file: ClientAnnotationProcessorTest.java

  15 
vote

@Test public void testListenUnlisten() throws Exception {
  final AtomicReference<Message> handshakeRef=new AtomicReference<>();
  final CountDownLatch handshakeLatch=new CountDownLatch(1);
  final AtomicReference<Message> connectRef=new AtomicReference<>();
  final CountDownLatch connectLatch=new CountDownLatch(1);
  final AtomicReference<Message> disconnectRef=new AtomicReference<>();
  final CountDownLatch disconnectLatch=new CountDownLatch(1);
@Service class S {
    @Listener(Channel.META_HANDSHAKE) private void metaHandshake(    Message handshake){
      handshakeRef.set(handshake);
      handshakeLatch.countDown();
    }
    @Listener(Channel.META_CONNECT) private void metaConnect(    Message connect){
      connectRef.set(connect);
      connectLatch.countDown();
    }
    @Listener(Channel.META_DISCONNECT) private void metaDisconnect(    Message connect){
      disconnectRef.set(connect);
      disconnectLatch.countDown();
    }
  }
  S s=new S();
  boolean processed=processor.process(s);
  assertTrue(processed);
  bayeuxClient.handshake();
  assertTrue(handshakeLatch.await(5,TimeUnit.SECONDS));
  Message handshake=handshakeRef.get();
  assertNotNull(handshake);
  assertTrue(handshake.isSuccessful());
  assertTrue(connectLatch.await(5,TimeUnit.SECONDS));
  Message connect=connectRef.get();
  assertNotNull(connect);
  assertTrue(connect.isSuccessful());
  processed=processor.deprocessCallbacks(s);
  assertTrue(processed);
  bayeuxClient.disconnect(1000);
}
 

Example 23

From project commons-j, under directory /src/main/java/nerds/antelax/commons/net/pubsub/.

Source file: ClientMessageHandler.java

  15 
vote

ClientMessageHandler(final ExecutorService callbackService){
  Preconditions.checkNotNull(callbackService,"ExecutorService cannot be null");
  activeChannel=new AtomicReference<Channel>(null);
  this.callbackService=callbackService;
  subscribers=new ConcurrentHashMap<String,Collection<PubSubClient.MessageCallback>>();
  lock=new ReentrantLock();
}
 

Example 24

From project CommunityCase, under directory /src/org/community/intellij/plugins/communitycase/checkin/.

Source file: PushActiveBranchesDialog.java

  15 
vote

/** 
 * Pushes selected commits synchronously in foreground.
 */
private void push(){
  final Collection<Root> rootsToPush=getRootsToPush();
  final AtomicReference<Collection<VcsException>> errors=new AtomicReference<Collection<VcsException>>();
  ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable(){
    public void run(){
      errors.set(executePushCommand(rootsToPush));
    }
  }
,Bundle.getString("push.active.pushing"),true,myProject);
  if (errors.get() != null && !errors.get().isEmpty()) {
    UiUtil.showOperationErrors(myProject,errors.get(),Bundle.getString("push.active.pushing"));
  }
  refreshTree(false,null);
}
 

Example 25

From project components-ness-httpserver_1, under directory /src/test/java/com/nesscomputing/httpserver/jetty/.

Source file: TestClasspathResourceHandler.java

  15 
vote

@Test public void testIfModified() throws Exception {
  final AtomicReference<String> holder=new AtomicReference<String>(null);
  final HttpClientResponseHandler<String> responseHandler=new ContentResponseHandler<String>(new StringContentConverter(){
    @Override public String convert(    final HttpClientResponse response,    final InputStream inputStream) throws IOException {
      holder.set(response.getHeader("Last-Modified"));
      return super.convert(response,inputStream);
    }
  }
);
  final String content=httpClient.get(baseUri + "/simple-content.txt",responseHandler).perform();
  Assert.assertNotNull(holder.get());
  Assert.assertEquals("this is simple content for a simple test\n",content);
  final HttpClientResponseHandler<String> responseHandler2=new ContentResponseHandler<String>(new StringContentConverter(){
    @Override public String convert(    final HttpClientResponse response,    final InputStream inputStream) throws IOException {
      Assert.assertEquals(304,response.getStatusCode());
      return null;
    }
  }
);
  final String content2=httpClient.get(baseUri + "/simple-content.txt",responseHandler2).addHeader("If-Modified-Since",holder.get()).perform();
  Assert.assertNull(content2);
}
 

Example 26

From project crash, under directory /shell/core/src/main/java/org/crsh/processor/jline/.

Source file: JLineProcessor.java

  15 
vote

public JLineProcessor(Shell shell,ConsoleReader reader,PrintWriter writer){
  this.shell=shell;
  this.reader=reader;
  this.writer=writer;
  this.current=new AtomicReference<ShellProcess>();
}
 

Example 27

From project curator, under directory /curator-client/src/main/java/com/netflix/curator/.

Source file: ConnectionState.java

  15 
vote

ConnectionState(ZookeeperFactory zookeeperFactory,EnsembleProvider ensembleProvider,int sessionTimeoutMs,int connectionTimeoutMs,Watcher parentWatcher,AtomicReference<TracerDriver> tracer){
  this.ensembleProvider=ensembleProvider;
  this.connectionTimeoutMs=connectionTimeoutMs;
  this.tracer=tracer;
  if (parentWatcher != null) {
    parentWatchers.offer(parentWatcher);
  }
  zooKeeper=new HandleHolder(zookeeperFactory,this,ensembleProvider,sessionTimeoutMs);
}
 

Example 28

From project Dempsy, under directory /lib-dempsyimpl/src/main/java/com/nokia/dempsy/cluster/zookeeper/.

Source file: ZookeeperSession.java

  15 
vote

protected ZookeeperSession(String connectString,int sessionTimeout) throws IOException {
  this.connectString=connectString;
  this.sessionTimeout=sessionTimeout;
  this.zkref=new AtomicReference<ZooKeeper>();
  ZooKeeper newZk=makeZooKeeperClient(connectString,sessionTimeout);
  if (newZk != null)   setNewZookeeper(newZk);
}
 

Example 29

From project DeuceSTM, under directory /src/test/org/deuce/utest/basic/.

Source file: AtomicBlockIDTest.java

  15 
vote

public void testAbort() throws Exception {
  final AtomicReference<Exception> error=new AtomicReference<Exception>();
  Thread thread=new Thread(new Runnable(){
    @Override public void run(){
      Context originalInstance=ContextDelegator.getInstance();
      ThreadLocal<Context> threadLocal=null;
      try {
        Field declaredField=ContextDelegator.class.getDeclaredField("THREAD_CONTEXT");
        declaredField.setAccessible(true);
        threadLocal=(ThreadLocal<Context>)declaredField.get(Thread.currentThread());
        MockContext context=new MockContext();
        threadLocal.set(context);
        blockA();
        Assert.assertEquals("a",context.getMetainf());
        int atomicBlockIdA=context.getAtomicBlockId();
        blockB();
        Assert.assertEquals("",context.getMetainf());
        int atomicBlockIdB=context.getAtomicBlockId();
        Assert.assertFalse(atomicBlockIdA == atomicBlockIdB);
        blockC();
        Assert.assertEquals("",context.getMetainf());
        int atomicBlockIdC=context.getAtomicBlockId();
        Assert.assertFalse(atomicBlockIdA == atomicBlockIdC);
        Assert.assertFalse(atomicBlockIdB == atomicBlockIdC);
      }
 catch (      Exception e) {
        error.equals(e);
      }
 finally {
        if (threadLocal != null)         threadLocal.set(originalInstance);
      }
    }
  }
);
  thread.start();
  thread.join();
  if (error.get() != null)   throw error.get();
}
 

Example 30

From project dimdwarf, under directory /dimdwarf-core/src/test/java/net/orfjackal/dimdwarf/context/.

Source file: TaskScopeSpec.java

  15 
vote

public void eachConcurrentScopeHasItsOwnInstances() throws InterruptedException {
  final AtomicReference<MyService> s1=new AtomicReference<MyService>();
  final AtomicReference<MyService> s2=new AtomicReference<MyService>();
  final CountDownLatch taskRunning=new CountDownLatch(2);
  final CountDownLatch gotInstance=new CountDownLatch(2);
  Thread t1=new Thread(new Runnable(){
    public void run(){
      ThreadContext.runInContext(contextProvider.get(),new Runnable(){
        public void run(){
          awaitForOthers(taskRunning);
          s1.set(injector.getInstance(MyService.class));
          awaitForOthers(gotInstance);
        }
      }
);
    }
  }
);
  Thread t2=new Thread(new Runnable(){
    public void run(){
      ThreadContext.runInContext(contextProvider.get(),new Runnable(){
        public void run(){
          awaitForOthers(taskRunning);
          s2.set(injector.getInstance(MyService.class));
          awaitForOthers(gotInstance);
        }
      }
);
    }
  }
);
  t1.setDaemon(true);
  t1.start();
  t2.setDaemon(true);
  t2.start();
  gotInstance.await();
  specify(s1.get(),should.not().equal(null));
  specify(s2.get(),should.not().equal(null));
  specify(s1.get(),should.not().equal(s2.get()));
}
 

Example 31

From project disruptor, under directory /src/test/java/com/lmax/disruptor/dsl/.

Source file: DisruptorTest.java

  15 
vote

@Test public void shouldSupportSpecifyingADefaultExceptionHandlerForEventProcessors() throws Exception {
  AtomicReference<Throwable> eventHandled=new AtomicReference<Throwable>();
  ExceptionHandler exceptionHandler=new StubExceptionHandler(eventHandled);
  RuntimeException testException=new RuntimeException();
  ExceptionThrowingEventHandler handler=new ExceptionThrowingEventHandler(testException);
  disruptor.handleExceptionsWith(exceptionHandler);
  disruptor.handleEventsWith(handler);
  publishEvent();
  final Throwable actualException=waitFor(eventHandled);
  assertSame(testException,actualException);
}
 

Example 32

From project Easy-Cassandra, under directory /src/main/java/org/easycassandra/persistence/.

Source file: ColumnUtil.java

  15 
vote

/** 
 * The method for set the new KeyValue in auto counting mode
 * @param object - the object
 * @param keyField - the key
 * @param columnFamily - the name of column
 * @param superColumnRef - reference of super column
 * @param keyStore - the name of key Store
 */
public static void setAutoCoutingKeyValue(Object object,Field keyField,String columnFamily,AtomicReference<ColumnFamilyIds> superColumnRef,String keyStore){
  if (!contains(keyField.getType())) {
    throw new EasyCassandraException(" There are not supported " + "auto counting  for this class, see: java.lang.String," + " java.lang.Long, java.lang.Integer, java.lang.Byte,"+ " java.lang.Short, java.math.BigInteger ");
  }
  Object id=superColumnRef.get().getId(columnFamily,keyStore);
  if (String.class.equals(keyField.getType())) {
    id=id.toString();
  }
 else   if (!BigInteger.class.equals(keyField.getType())) {
    id=ReflectionUtil.valueOf(keyField.getType(),id.toString());
  }
  ReflectionUtil.setMethod(object,keyField,id);
}
 

Example 33

From project erjang, under directory /src/main/java/erjang/m/ets/.

Source file: ETable.java

  15 
vote

ETable(EProc owner,EAtom type,EInteger tid,EAtom aname,EAtom access,int keypos,boolean is_named,EInternalPID heir_pid,EObject heir_data,APersistentMap map){
  this.type=type;
  this.is_named=is_named;
  this.owner=new WeakReference<EProc>(owner);
  this.tid=tid;
  this.aname=aname;
  this.access=access;
  this.keypos1=keypos;
  this.heirPID=heir_pid;
  this.heirData=heir_data;
  try {
    this.mapRef=new AtomicReference<IPersistentMap<EObject,Object>>(map);
  }
 catch (  Exception e) {
    throw new ErlangError(am_stm);
  }
  empty=map;
  owner.add_exit_hook(this);
}
 

Example 34

From project Flume-Hive, under directory /src/javatest/com/cloudera/flume/agent/.

Source file: TestFlumeNodeMain.java

  15 
vote

@Test public void testOneshot() throws InterruptedException {
  final String[] simple={"-1","-n","test","-c","test: text(\"" + ExampleData.APACHE_REGEXES + "\") | null;"};
  final AtomicReference<Exception> ref=new AtomicReference<Exception>();
  Thread t=new Thread(){
    public void run(){
      try {
        FlumeNode.setup(simple);
      }
 catch (      Exception e) {
        ref.set(e);
      }
    }
  }
;
  t.start();
  Thread.sleep(5000);
  if (ref.get() != null) {
    fail("an exception was thrown");
  }
}
 

Example 35

From project Foglyn, under directory /com.foglyn.core/src/com/foglyn/core/.

Source file: FogBugzClientFactory.java

  15 
vote

FogBugzClientFactory(HttpClient httpClient){
  Assert.isNotNull(httpClient);
  this.httpClient=httpClient;
  this.clients=new HashMap<Pair<String,AuthenticationCredentials>,FogBugzClient>();
  this.repositoryLocationFactory=new AtomicReference<TaskRepositoryLocationFactory>(new TaskRepositoryLocationFactory());
}
 

Example 36

From project gatein-common, under directory /logging/src/test/java/org/gatein/common/logging/.

Source file: LogTestCase.java

  15 
vote

public void testConcurrentGetRace() throws Exception {
  final ReentrantLock lock=LoggerFactoryImpl.getLock();
  lock.lock();
  final AtomicReference<Logger> loggerRef=new AtomicReference<Logger>();
  final AtomicBoolean done=new AtomicBoolean();
  Thread t=new Thread(){
    public void run(){
      Logger logger=LoggerFactory.getLogger("testConcurrentGetRace");
      loggerRef.set(logger);
      done.set(true);
    }
  }
;
  t.start();
  while (!lock.hasQueuedThread(t)) {
    Thread.sleep(1);
  }
  assertEquals(null,LoggerFactoryImpl.peekLogger("testConcurrentGetRace"));
  Logger logger=LoggerFactory.getLogger("testConcurrentGetRace");
  assertNotNull(logger);
  lock.unlock();
  while (!done.get()) {
    Thread.sleep(1);
  }
  assertSame(logger,loggerRef.get());
}
 

Example 37

From project Gemini-Blueprint, under directory /core/src/test/java/org/eclipse/gemini/blueprint/blueprint/container/.

Source file: TypeFactoryTest.java

  15 
vote

@Test @Ignore public void testTypedReference() throws Exception {
  ReifiedType tp=getReifiedTypeFor("typedReference");
  assertEquals(AtomicReference.class,tp.getRawClass());
  assertEquals(1,tp.size());
  assertEquals(Boolean.class,tp.getActualTypeArgument(0).getRawClass());
}
 

Example 38

From project geronimo-xbean, under directory /xbean-blueprint/src/test/java/org/apache/xbean/blueprint/generator/.

Source file: ModelTest.java

  15 
vote

private void validate(InputStream xml,final File xsd) throws ParserConfigurationException, SAXException, IOException {
  assertNotNull(xml);
  DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
  factory.setNamespaceAware(true);
  factory.setValidating(true);
  factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage","http://www.w3.org/2001/XMLSchema");
  final AtomicReference<SAXParseException> error=new AtomicReference<SAXParseException>();
  DocumentBuilder builder=factory.newDocumentBuilder();
  builder.setErrorHandler(new ErrorHandler(){
    public void warning(    SAXParseException exception) throws SAXException {
      error.set(exception);
    }
    public void error(    SAXParseException exception) throws SAXException {
      error.set(exception);
    }
    public void fatalError(    SAXParseException exception) throws SAXException {
      error.set(exception);
    }
  }
);
  builder.setEntityResolver(new EntityResolver(){
    public InputSource resolveEntity(    String publicId,    String systemId) throws SAXException, IOException {
      InputSource source=null;
      if (source == null && "http://xbean.apache.org/test.xsd".equals(systemId)) {
        source=new InputSource(new FileInputStream(xsd));
        source.setPublicId(publicId);
        source.setSystemId(systemId);
      }
      return source;
    }
  }
);
  builder.parse(xml);
  if (error.get() != null) {
    error.get().printStackTrace();
    fail("Validation failed: " + error.get().getMessage());
  }
}
 

Example 39

From project gerrit-trigger-plugin, under directory /gerrithudsontrigger/src/test/java/com/sonyericsson/hudson/plugins/gerrit/trigger/mock/.

Source file: DuplicatesUtil.java

  15 
vote

/** 
 * Waits for a build to start for the specified event.
 * @param event     the event to monitor.
 * @param timeoutMs the maximum time in ms to wait for the build to start.
 * @return the build that started.
 */
public static AbstractBuild waitForBuildToStart(PatchsetCreated event,int timeoutMs){
  long startTime=System.currentTimeMillis();
  final AtomicReference<AbstractBuild> ref=new AtomicReference<AbstractBuild>();
  event.addListener(new GerritEventLifeCycleAdaptor(){
    @Override public void buildStarted(    PatchsetCreated event,    AbstractBuild build){
      ref.getAndSet(build);
    }
  }
);
  while (ref.get() == null) {
    if (System.currentTimeMillis() - startTime >= timeoutMs) {
      throw new RuntimeException("Timeout!");
    }
    try {
      Thread.sleep(500);
    }
 catch (    InterruptedException e) {
      System.err.println("Interrupted while waiting!");
    }
  }
  return ref.get();
}
 

Example 40

From project GNDMS, under directory /stuff/test-src/de/zib/gndms/stuff/confuror/.

Source file: ConfigHolderTest.java

  15 
vote

@Test public void pathTest() throws IOException, ConfigEditor.UpdateRejectedException {
  ConfigEditor editor=tree.newEditor(visitor);
  JsonNode init=parseSingle(factory,"{ 'a': 12, 'b': { 'x': { 'c' : 4 } } }");
  tree.update(editor,init);
  final AtomicReference<Object[]> ref=new AtomicReference<Object[]>(null);
  ConfigEditor reportingEditor=tree.newEditor(new ConfigEditor.Visitor(){
    public ObjectMapper getObjectMapper(){
      return objectMapper;
    }
    public void updateNode(    @NotNull ConfigEditor.Update updater){
      ref.getAndSet(updater.getPath());
      updater.accept();
    }
  }
);
  tree.update(reportingEditor,parseSingle(factory,"{ '+b': { '+x': { 'q': 5 } } }"));
  final Object[] result=ref.get();
  Assert.assertTrue(result.length == 3);
  Assert.assertTrue(result[0].equals("b"));
  Assert.assertTrue(result[1].equals("x"));
  Assert.assertTrue(result[2].equals("q"));
}
 

Example 41

From project guice-jit-providers, under directory /core/test/com/google/inject/.

Source file: BindingOrderTest.java

  15 
vote

public void testBindingWithExtraThreads() throws InterruptedException {
  final CountDownLatch ready=new CountDownLatch(1);
  final CountDownLatch done=new CountDownLatch(1);
  final AtomicReference<B> ref=new AtomicReference<B>();
  final Object createsAThread=new Object(){
    @Inject void createAnotherThread(    final Injector injector){
      new Thread(){
        public void run(){
          ready.countDown();
          A a=injector.getInstance(A.class);
          ref.set(a.b);
          done.countDown();
        }
      }
.start();
      try {
        ready.await();
      }
 catch (      InterruptedException e) {
        throw new RuntimeException(e);
      }
    }
  }
;
  Guice.createInjector(new AbstractModule(){
    protected void configure(){
      requestInjection(createsAThread);
      bind(A.class).toInstance(new A());
    }
  }
);
  done.await();
  assertNotNull(ref.get());
}
 

Example 42

From project hama, under directory /core/src/main/java/org/apache/hama/bsp/.

Source file: TaskRunner.java

  15 
vote

BspChildRunner(List<String> commands,File workDir){
  this.commands=commands;
  this.workDir=workDir;
  this.sched=Executors.newScheduledThreadPool(1);
  this.future=new AtomicReference<ScheduledFuture<Object>>();
}
 

Example 43

From project hbase-rdf_1, under directory /src/main/java/com/talis/hbase/rdf/layout/.

Source file: LoaderTuplesNodes.java

  15 
vote

private void init(){
  if (initialized)   return;
  tupleLoaders=new HashMap<TableDesc[],TupleLoader>();
  currentLoader=null;
  count=0;
  if (threading) {
    queue=new ArrayBlockingQueue<TupleChange>(chunkSize);
    threadException=new AtomicReference<Throwable>();
    threadFlushing=new AtomicBoolean();
    commitThread=new Thread(new Commiter());
    commitThread.setDaemon(true);
    commitThread.start();
    LOG.debug("Threading started");
  }
  initialized=true;
}
 

Example 44

From project httpClient, under directory /httpclient/src/test/java/org/apache/http/impl/client/integration/.

Source file: TestAbortHandling.java

  15 
vote

/** 
 * Tests that if abort is called on an  {@link AbortableHttpRequest} while{@link DefaultRequestDirector} is allocating a connection, that theconnection is properly aborted.
 */
@Test public void testAbortInAllocate() throws Exception {
  CountDownLatch connLatch=new CountDownLatch(1);
  CountDownLatch awaitLatch=new CountDownLatch(1);
  final ConMan conMan=new ConMan(connLatch,awaitLatch);
  final AtomicReference<Throwable> throwableRef=new AtomicReference<Throwable>();
  final CountDownLatch getLatch=new CountDownLatch(1);
  final HttpClient client=new HttpClientBuilder().setConnectionManager(conMan).build();
  final HttpContext context=new BasicHttpContext();
  final HttpGet httpget=new HttpGet("http://www.example.com/a");
  this.httpclient=client;
  new Thread(new Runnable(){
    public void run(){
      try {
        client.execute(httpget,context);
      }
 catch (      Throwable t) {
        throwableRef.set(t);
      }
 finally {
        getLatch.countDown();
      }
    }
  }
).start();
  Assert.assertTrue("should have tried to get a connection",connLatch.await(1,TimeUnit.SECONDS));
  httpget.abort();
  Assert.assertTrue("should have finished get request",getLatch.await(1,TimeUnit.SECONDS));
  Assert.assertTrue("should be instanceof IOException, was: " + throwableRef.get(),throwableRef.get() instanceof IOException);
  Assert.assertTrue("cause should be InterruptedException, was: " + throwableRef.get().getCause(),throwableRef.get().getCause() instanceof InterruptedException);
}
 

Example 45

From project httptunnel, under directory /src/main/java/com/yammer/httptunnel/client/.

Source file: HttpTunnelClientChannel.java

  15 
vote

/** 
 * @see HttpTunnelClientChannelFactory#newChannel(ChannelPipeline)
 */
protected HttpTunnelClientChannel(ChannelFactory factory,ChannelPipeline pipeline,HttpTunnelClientChannelSink sink,ClientSocketChannelFactory outboundFactory,ChannelGroup realConnections){
  super(null,factory,pipeline,sink);
  this.outboundFactory=outboundFactory;
  final WorkerCallbacks callbackProxy=new WorkerCallbacks();
  incomingBuffer=new IncomingBuffer<ChannelBuffer>(this);
  Metrics.newGauge(HttpTunnelClientChannel.class,"incomingBuffer",new Gauge<Integer>(){
    @Override public Integer value(){
      return incomingBuffer.size();
    }
  }
);
  sendChannel=outboundFactory.newChannel(Channels.pipeline(new SimpleChannelHandler()));
  pollChannel=outboundFactory.newChannel(Channels.pipeline(new SimpleChannelHandler()));
  config=new HttpTunnelClientChannelConfig(sendChannel.getConfig(),pollChannel.getConfig());
  saturationManager=new SaturationManager(config.getWriteBufferLowWaterMark(),config.getWriteBufferHighWaterMark());
  sendHttpHandler=new HttpTunnelClientChannelProxyHandler();
  sendHandler=new HttpTunnelClientChannelSendHandler(callbackProxy);
  pollHttpHandler=new HttpTunnelClientChannelProxyHandler();
  pollHandler=new HttpTunnelClientChannelPollHandler(callbackProxy);
  opened=new AtomicBoolean(true);
  bindState=new AtomicReference<BindState>(BindState.UNBOUND);
  connectState=new AtomicReference<ConnectState>(ConnectState.DISCONNECTED);
  connectFuture=new AtomicReference<ChannelFuture>(null);
  tunnelId=null;
  remoteAddress=null;
  this.initSendPipeline(sendChannel.getPipeline());
  this.initPollPipeline(pollChannel.getPipeline());
  realConnections.add(sendChannel);
  realConnections.add(pollChannel);
  Channels.fireChannelOpen(this);
}
 

Example 46

From project incubator-s4, under directory /subprojects/s4-comm/src/main/java/org/apache/s4/comm/topology/.

Source file: AssignmentFromZK.java

  15 
vote

@Inject public AssignmentFromZK(@Named("s4.cluster.name") String clusterName,@Named("s4.cluster.zk_address") String zookeeperAddress,@Named("s4.cluster.zk_session_timeout") int sessionTimeout,@Named("s4.cluster.zk_connection_timeout") int connectionTimeout) throws Exception {
  this.clusterName=clusterName;
  this.connectionTimeout=connectionTimeout;
  taskPath="/s4/clusters/" + clusterName + "/tasks";
  processPath="/s4/clusters/" + clusterName + "/process";
  lock=new ReentrantLock();
  clusterNodeRef=new AtomicReference<ClusterNode>();
  taskAcquired=lock.newCondition();
  currentlyOwningTask=new AtomicBoolean(false);
  try {
    machineId=InetAddress.getLocalHost().getCanonicalHostName();
  }
 catch (  UnknownHostException e) {
    logger.warn("Unable to get hostname",e);
    machineId="UNKNOWN";
  }
  zkClient=new ZkClient(zookeeperAddress,sessionTimeout,connectionTimeout);
  ZkSerializer serializer=new ZNRecordSerializer();
  zkClient.setZkSerializer(serializer);
}
 

Example 47

From project indextank-engine, under directory /cojen-2.2.1-sources/org/cojen/util/.

Source file: BelatedCreator.java

  15 
vote

/** 
 * Returns a Constructor that accepts an AtomicReference to the wrapped object.
 */
private Constructor<T> getWrapper(){
  Class<T> clazz;
synchronized (cWrapperCache) {
    clazz=(Class<T>)cWrapperCache.get(mType);
    if (clazz == null) {
      clazz=createWrapper();
      cWrapperCache.put(mType,clazz);
    }
  }
  try {
    return clazz.getConstructor(AtomicReference.class);
  }
 catch (  NoSuchMethodException e) {
    ThrowUnchecked.fire(e);
    return null;
  }
}
 

Example 48

From project jackrabbit-oak, under directory /oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/observation/.

Source file: ChangeProcessor.java

  15 
vote

public ChangeProcessor(ObservationManagerImpl observationManager,EventListener listener,ChangeFilter filter){
  this.observationManager=observationManager;
  this.namePathMapper=observationManager.getNamePathMapper();
  this.changeExtractor=observationManager.getChangeExtractor();
  this.listener=listener;
  filterRef=new AtomicReference<ChangeFilter>(filter);
}
 

Example 49

From project jboss-classfilewriter, under directory /src/main/java/org/jboss/classfilewriter/code/.

Source file: LookupSwitchBuilder.java

  15 
vote

/** 
 * Adds a value to the table that is at a location yet to be written. After this lookup switch has been written then the BranchEnd can be retrieved from the returned reference.
 * @param value The value to add to the lookup table
 * @return A reference to the BranchEnd that will be created.
 */
public AtomicReference<BranchEnd> add(int value){
  final AtomicReference<BranchEnd> end=new AtomicReference<BranchEnd>();
  ValuePair vp=new ValuePair(value,end);
  values.add(vp);
  return end;
}
 

Example 50

From project jboss-logmanager, under directory /src/test/java/org/jboss/logmanager/.

Source file: FilterTests.java

  15 
vote

public void testSubstitueFilter0(){
  final Filter filter=new SubstituteFilter(Pattern.compile("test"),"lunch",true);
  final AtomicReference<String> result=new AtomicReference<String>();
  final Handler handler=new MessageCheckingHandler(result);
  final Logger logger=Logger.getLogger("filterTest");
  logger.setUseParentHandlers(false);
  logger.addHandler(handler);
  logger.setLevel(Level.INFO);
  logger.setFilter(filter);
  handler.setLevel(Level.INFO);
  logger.info("This is a test test.");
  assertEquals("Substitution was not correctly applied","This is a lunch lunch.",result.get());
}
 

Example 51

From project jboss-msc, under directory /src/test/java/org/jboss/msc/inject/.

Source file: AtomicReferenceInjectorTestCase.java

  15 
vote

@Test public void atomicReferenceInjection() throws Exception {
  final AtomicReference<String> reference=new AtomicReference<String>("");
  final Injector<String> injector=new AtomicReferenceInjector<String>(reference);
  injector.inject("new value");
  assertEquals("new value",reference.get());
  injector.uninject();
  assertNull(reference.get());
  injector.inject("another value");
  assertEquals("another value",reference.get());
  injector.inject(null);
  assertNull(reference.get());
}
 

Example 52

From project jdbi, under directory /src/main/java/org/skife/jdbi/v2/.

Source file: Query.java

  15 
vote

/** 
 * Used to execute the query and traverse the result set with a accumulator. <a href="http://en.wikipedia.org/wiki/Fold_(higher-order_function)">Folding</a> over the result involves invoking a callback for each row, passing into the callback the return value from the previous function invocation.
 * @param accumulator The initial accumulator value
 * @param folder      Defines the function which will fold over the result set.
 * @return The return value from the last invocation of {@link Folder#fold(Object,java.sql.ResultSet)}
 * @see org.skife.jdbi.v2.Folder
 * @deprecated Use {@link Query#fold(Object,Folder3)}
 */
public <AccumulatorType>AccumulatorType fold(AccumulatorType accumulator,final Folder2<AccumulatorType> folder){
  final AtomicReference<AccumulatorType> acc=new AtomicReference<AccumulatorType>(accumulator);
  try {
    this.internalExecute(new QueryResultSetMunger<Void>(this){
      public Void munge(      ResultSet rs) throws SQLException {
        while (rs.next()) {
          acc.set(folder.fold(acc.get(),rs,getContext()));
        }
        return null;
      }
    }
);
    return acc.get();
  }
  finally {
    cleanup();
  }
}
 

Example 53

From project JitCask, under directory /src/com/afewmoreamps/util/.

Source file: COWMap.java

  15 
vote

public COWMap(Map<K,V> map){
  if (map == null) {
    throw new IllegalArgumentException("Wrapped map cannot be null");
  }
  m_map=new AtomicReference<ImmutableMap<K,V>>(new Builder<K,V>().putAll(map).build());
}
 

Example 54

From project jredis, under directory /core/ri/src/main/java/org/jredis/ri/alphazero/connection/.

Source file: ChunkedPipelineConnection.java

  15 
vote

/** 
 * Adds self to the listeners of the enclosing  {@link Connection} instance.
 */
public ResponseHandler(){
  ChunkedPipelineConnection.this.addListener(this);
  this.work_flag=true;
  this.alive_flag=new AtomicBoolean(false);
  this.thread=new AtomicReference<Thread>(null);
}
 

Example 55

From project JsTestDriver, under directory /JsTestDriver/src/com/google/jstestdriver/.

Source file: SlaveBrowser.java

  15 
vote

public SlaveBrowser(Time time,String id,BrowserInfo browserInfo,long timeout,HandlerPathPrefix prefix,String mode,RunnerType type){
  this.time=time;
  this.timeout=timeout;
  this.id=id;
  this.browserInfo=browserInfo;
  this.prefix=prefix;
  this.mode=mode;
  this.type=type;
  lastHeartbeat=new AtomicReference<Instant>(new Instant(0));
}
 

Example 56

From project kernel_1, under directory /exo.kernel.component.common/src/main/java/org/exoplatform/services/naming/.

Source file: ExoContainerContextFactory.java

  15 
vote

public ExoContainerCtx(Hashtable<?,?> env){
  this.env=env == null ? null : (Hashtable)env.clone();
  this.container=ExoContainerContext.getCurrentContainerIfPresent();
  if (container != null) {
    AtomicReference<Map<String,Object>> ref=ALL_BINDINGS.get(container);
    if (ref == null) {
synchronized (ExoContainerCtx.class) {
        if (ref == null) {
          Map<ExoContainer,AtomicReference<Map<String,Object>>> tempAllBindings=new HashMap<ExoContainer,AtomicReference<Map<String,Object>>>(ALL_BINDINGS);
          tempAllBindings.put(container,ref=new AtomicReference<Map<String,Object>>(new HashMap<String,Object>()));
          ALL_BINDINGS=tempAllBindings;
        }
      }
    }
    this.bindingsRef=ref;
  }
}
 

Example 57

From project mcore, under directory /src/com/massivecraft/mcore4/xlib/mongodb/.

Source file: ReplicaSetStatus.java

  15 
vote

UpdatableNode(ServerAddress addr,List<UpdatableNode> all,AtomicReference<Logger> logger,Mongo mongo,MongoOptions mongoOptions,AtomicReference<String> setName,AtomicReference<String> lastPrimarySignal){
  _addr=addr;
  _all=all;
  _mongoOptions=mongoOptions;
  _port=new DBPort(addr,null,_mongoOptions);
  _names.add(addr.toString());
  _logger=logger;
  _mongo=mongo;
  _setName=setName;
  _lastPrimarySignal=lastPrimarySignal;
}
 

Example 58

From project menagerie, under directory /src/test/java/org/menagerie/locks/.

Source file: ReentrantZkReadWriteLock2ReadLockTest.java

  15 
vote

@Test(timeout=1000l) public void testReadLockInterruptible() throws Exception {
  final CyclicBarrier barrier=new CyclicBarrier(2);
  final ReadWriteLock rwLock=new ReentrantZkReadWriteLock2(baseLockPath,zkSessionManager);
  final AtomicReference<Thread> otherThread=new AtomicReference<Thread>();
  Future<Boolean> future=testService.submit(new Callable<Boolean>(){
    @Override public Boolean call() throws Exception {
      otherThread.set(Thread.currentThread());
      Lock readLock=rwLock.readLock();
      barrier.await();
      try {
        readLock.lockInterruptibly();
      }
 catch (      InterruptedException ie) {
        return true;
      }
      return false;
    }
  }
);
  final Lock writeLock=rwLock.writeLock();
  writeLock.lock();
  try {
    barrier.await();
    otherThread.get().interrupt();
    boolean interrupted=future.get();
    assertTrue("Other thread was not interrupted!",interrupted);
  }
  finally {
    writeLock.unlock();
  }
}
 

Example 59

From project Metamorphosis, under directory /metamorphosis-client/src/test/java/com/taobao/metamorphosis/client/consumer/.

Source file: FetchRequestQueueUnitTest.java

  15 
vote

@Test public void testTakeWaitingOfferedDelayed() throws Exception {
  final AtomicReference<FetchRequest> offered=new AtomicReference<FetchRequest>();
  final AtomicBoolean done=new AtomicBoolean();
  new Thread(){
    @Override public void run(){
      try {
        offered.set(FetchRequestQueueUnitTest.this.fetchRequestQueue.take());
        done.set(true);
      }
 catch (      final InterruptedException e) {
      }
    }
  }
.start();
  Thread.sleep(1000);
  final FetchRequest request=new FetchRequest(1000);
  this.fetchRequestQueue.offer(request);
  while (!done.get()) {
    Thread.sleep(500);
  }
  assertSame(offered.get(),request);
}
 

Example 60

From project mongo-java-driver, under directory /src/main/com/mongodb/.

Source file: ReplicaSetStatus.java

  15 
vote

UpdatableReplicaSetNode(ServerAddress addr,List<UpdatableReplicaSetNode> all,AtomicReference<Logger> logger,Mongo mongo,MongoOptions mongoOptions,AtomicReference<String> lastPrimarySignal){
  super(addr,mongo,mongoOptions);
  _all=all;
  _names.add(addr.toString());
  _logger=logger;
  _lastPrimarySignal=lastPrimarySignal;
}
 

Example 61

From project mungbean, under directory /mungbean-java/src/main/java/mungbean/clojure/.

Source file: ClojureDBCollection.java

  15 
vote

public IPersistentCollection query(Query query,final IFn callback){
  final AtomicReference<IPersistentCollection> result=new AtomicReference<IPersistentCollection>(PersistentList.EMPTY);
  query(query,new QueryCallback<IPersistentMap>(){
    @Override public boolean process(    IPersistentMap item){
      try {
        result.set(result.get().cons(callback.invoke(item)));
        return true;
      }
 catch (      Exception e) {
        throw new RuntimeException(e);
      }
    }
  }
);
  return result.get();
}
 

Example 62

From project mylyn.builds, under directory /org.eclipse.mylyn.builds.core/src/org/eclipse/mylyn/builds/internal/core/operations/.

Source file: AbstractElementOperation.java

  15 
vote

protected List<T> doInitInput(){
  final AtomicReference<List<T>> input=new AtomicReference<List<T>>();
  getService().getRealm().syncExec(new Runnable(){
    public void run(){
      List<T> elements=doSyncInitInput();
      register(elements);
      input.set(elements);
    }
  }
);
  return input.get();
}
 

Example 63

From project nettosphere, under directory /server/src/test/java/org/atmosphere/nettosphere/test/.

Source file: NettyAtmosphereTest.java

  15 
vote

@Test public void webSocketHandlerTest() throws Exception {
  final CountDownLatch l=new CountDownLatch(1);
  Config config=new Config.Builder().port(port).host("127.0.0.1").handler(new Handler(){
    @Override public void handle(    AtmosphereResource r){
      r.getResponse().write("Hello World from Nettosphere").closeStreamOrWriter();
    }
  }
).build();
  server=new Nettosphere.Builder().config(config).build();
  assertNotNull(server);
  server.start();
  final AtomicReference<String> response=new AtomicReference<String>();
  AsyncHttpClient c=new AsyncHttpClient();
  WebSocket webSocket=c.prepareGet(wsUrl).execute(new WebSocketUpgradeHandler.Builder().build()).get();
  assertNotNull(webSocket);
  webSocket.addWebSocketListener(new WebSocketTextListener(){
    @Override public void onMessage(    String message){
      response.set(message);
      l.countDown();
    }
    @Override public void onFragment(    String fragment,    boolean last){
    }
    @Override public void onOpen(    WebSocket websocket){
    }
    @Override public void onClose(    WebSocket websocket){
    }
    @Override public void onError(    Throwable t){
    }
  }
);
  l.await(5,TimeUnit.SECONDS);
  webSocket.close();
  assertEquals(response.get(),"Hello World from Nettosphere");
}