org.apache.curator.utils.ThreadUtils Java Examples

The following examples show how to use org.apache.curator.utils.ThreadUtils. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DiscoveryResource.java    From curator with Apache License 2.0 6 votes vote down vote up
@GET
@Path("v1/service/{name}")
@Produces(MediaType.APPLICATION_JSON)
public Response     getAll(@PathParam("name") String name)
{
    try
    {
        Collection<ServiceInstance<T>>  instances = context.getServiceDiscovery().queryForInstances(name);
        return Response.ok(new ServiceInstances<T>(instances)).build();
    }
    catch ( Exception e )
    {
        ThreadUtils.checkInterrupted(e);
        log.error(String.format("Trying to get instances from service (%s)", name), e);
        return Response.serverError().build();
    }
}
 
Example #2
Source File: TreeCache.java    From xian with Apache License 2.0 6 votes vote down vote up
private void callListeners(final TreeCacheEvent event)
{
    listeners.forEach(new Function<TreeCacheListener, Void>()
    {
        @Override
        public Void apply(TreeCacheListener listener)
        {
            try
            {
                listener.childEvent(client, event);
            }
            catch ( Exception e )
            {
                ThreadUtils.checkInterrupted(e);
                handleException(e);
            }
            return null;
        }
    });
}
 
Example #3
Source File: TreeCache.java    From xian with Apache License 2.0 6 votes vote down vote up
private void publishEvent(final TreeCacheEvent event)
{
    if ( treeState.get() != TreeState.CLOSED )
    {
        LOG.debug("publishEvent: {}", event);
        executorService.submit(new Runnable()
        {
            @Override
            public void run()
            {
                {
                    try
                    {
                        callListeners(event);
                    }
                    catch ( Exception e )
                    {
                        ThreadUtils.checkInterrupted(e);
                        handleException(e);
                    }
                }
            }
        });
    }
}
 
Example #4
Source File: LeaderLatch.java    From xian with Apache License 2.0 6 votes vote down vote up
private synchronized void internalStart()
{
    if ( state.get() == State.STARTED )
    {
        client.getConnectionStateListenable().addListener(listener);
        try
        {
            reset();
        }
        catch ( Exception e )
        {
            ThreadUtils.checkInterrupted(e);
            log.error("An error occurred checking resetting leadership.", e);
        }
    }
}
 
Example #5
Source File: FailedOperationManager.java    From curator with Apache License 2.0 6 votes vote down vote up
void addFailedOperation(T details)
{
    if ( debugListener != null )
    {
        debugListener.pathAddedForGuaranteedOperation(details);
    }
    
    
    if ( client.getState() == CuratorFrameworkState.STARTED )
    {
        log.debug("Details being added to guaranteed operation set: " + details);
        try
        {
            executeGuaranteedOperationInBackground(details);
        }
        catch ( Exception e )
        {
            ThreadUtils.checkInterrupted(e);
            addFailedOperation(details);
        }
    }
}
 
Example #6
Source File: PathChildrenCache.java    From xian with Apache License 2.0 6 votes vote down vote up
void callListeners(final PathChildrenCacheEvent event)
{
    listeners.forEach
        (
            new Function<PathChildrenCacheListener, Void>()
            {
                @Override
                public Void apply(PathChildrenCacheListener listener)
                {
                    try
                    {
                        listener.childEvent(client, event);
                    }
                    catch ( Exception e )
                    {
                        ThreadUtils.checkInterrupted(e);
                        handleException(e);
                    }
                    return null;
                }
            }
        );
}
 
Example #7
Source File: PersistentNode.java    From xian with Apache License 2.0 6 votes vote down vote up
@Override
public void close() throws IOException
{
    if ( !state.compareAndSet(State.STARTED, State.CLOSED) )
    {
        return;
    }

    client.getConnectionStateListenable().removeListener(connectionStateListener);

    try
    {
        deleteNode();
    }
    catch ( Exception e )
    {
        ThreadUtils.checkInterrupted(e);
        throw new IOException(e);
    }
}
 
Example #8
Source File: MappingListenerManager.java    From curator with Apache License 2.0 6 votes vote down vote up
@Override
public void forEach(Consumer<V> function)
{
    for ( ListenerEntry<V> entry : listeners.values() )
    {
        entry.executor.execute(() -> {
            try
            {
                function.accept(entry.listener);
            }
            catch ( Throwable e )
            {
                ThreadUtils.checkInterrupted(e);
                log.error(String.format("Listener (%s) threw an exception", entry.listener), e);
            }
        });
    }
}
 
Example #9
Source File: LeaderLatch.java    From curator with Apache License 2.0 6 votes vote down vote up
private synchronized void internalStart()
{
    if ( state.get() == State.STARTED )
    {
        client.getConnectionStateListenable().addListener(listener);
        try
        {
            reset();
        }
        catch ( Exception e )
        {
            ThreadUtils.checkInterrupted(e);
            log.error("An error occurred checking resetting leadership.", e);
        }
    }
}
 
Example #10
Source File: CuratorFrameworkImpl.java    From curator with Apache License 2.0 6 votes vote down vote up
private void processEvent(final CuratorEvent curatorEvent)
{
    if ( curatorEvent.getType() == CuratorEventType.WATCHED )
    {
        validateConnection(curatorEvent.getWatchedEvent().getState());
    }

    listeners.forEach(listener ->
    {
        try
        {
            OperationTrace trace = client.startAdvancedTracer("EventListener");
            listener.eventReceived(CuratorFrameworkImpl.this, curatorEvent);
            trace.commit();
        }
        catch ( Exception e )
        {
            ThreadUtils.checkInterrupted(e);
            logError("Event listener threw exception", e);
        }
    });
}
 
Example #11
Source File: InterProcessSemaphore.java    From xian with Apache License 2.0 6 votes vote down vote up
/**
 * <p>Acquire <code>qty</code> leases. If there are not enough leases available, this method
 * blocks until either the maximum number of leases is increased enough or other clients/processes
 * close enough leases.</p>
 *
 * <p>The client must close the leases when it is done with them. You should do this in a
 * <code>finally</code> block. NOTE: You can use {@link #returnAll(Collection)} for this.</p>
 *
 * @param qty number of leases to acquire
 * @return the new leases
 * @throws Exception ZK errors, interruptions, etc.
 */
public Collection<Lease> acquire(int qty) throws Exception
{
    Preconditions.checkArgument(qty > 0, "qty cannot be 0");

    ImmutableList.Builder<Lease>    builder = ImmutableList.builder();
    try
    {
        while ( qty-- > 0 )
        {
            String      path = internals.attemptLock(-1, null, null);
            builder.add(makeLease(path));
        }
    }
    catch ( Exception e )
    {
        ThreadUtils.checkInterrupted(e);
        returnAll(builder.build());
        throw e;
    }
    return builder.build();
}
 
Example #12
Source File: CuratorZookeeperClient.java    From curator with Apache License 2.0 6 votes vote down vote up
/**
 * Close this client object as the {@link #close() } method.
 * This method will wait for internal resources to be released.
 * 
 * @param waitForShutdownTimeoutMs timeout (in milliseconds) to wait for resources to be released.
 *                  Use zero or a negative value to skip the wait.
 */
public void close(int waitForShutdownTimeoutMs)
{
    log.debug("Closing, waitForShutdownTimeoutMs {}", waitForShutdownTimeoutMs);

    started.set(false);
    try
    {
        state.close(waitForShutdownTimeoutMs);
    }
    catch ( IOException e )
    {
        ThreadUtils.checkInterrupted(e);
        log.error("", e);
    }
}
 
Example #13
Source File: NamespaceWatcher.java    From xian with Apache License 2.0 6 votes vote down vote up
@Override
public void process(WatchedEvent event)
{
    if ( client != null )
    {
        if ( actualWatcher != null )
        {
            actualWatcher.process(new NamespaceWatchedEvent(client, event));
        }
        else if ( curatorWatcher != null )
        {
            try
            {
                curatorWatcher.process(new NamespaceWatchedEvent(client, event));
            }
            catch ( Exception e )
            {
                ThreadUtils.checkInterrupted(e);
                client.logError("Watcher exception", e);
            }
        }
    }
}
 
Example #14
Source File: JsonServiceInstancesMarshaller.java    From curator with Apache License 2.0 6 votes vote down vote up
@Override
public ServiceInstances<T> readFrom(Class<ServiceInstances<T>> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException
{
    try
    {
        List<ServiceInstance<T>>    instances = Lists.newArrayList();
        ObjectMapper                mapper = new ObjectMapper();
        JsonNode                    tree = mapper.reader().readTree(entityStream);
        for ( int i = 0; i < tree.size(); ++i )
        {
            JsonNode                    node = tree.get(i);
            ServiceInstance<T> instance = JsonServiceInstanceMarshaller.readInstance(node, context);
            instances.add(instance);
        }
        return new ServiceInstances<T>(instances);
    }
    catch ( Exception e )
    {
        ThreadUtils.checkInterrupted(e);
        throw new WebApplicationException(e);
    }
}
 
Example #15
Source File: InstanceCleanup.java    From curator with Apache License 2.0 6 votes vote down vote up
private void checkService(String name)
{
    try
    {
        Collection<ServiceInstance<Object>>     instances = discovery.queryForInstances(name);
        for ( ServiceInstance<Object> instance : instances )
        {
            if ( instance.getServiceType() == ServiceType.STATIC )
            {
                if ( (System.currentTimeMillis() - instance.getRegistrationTimeUTC()) > instanceRefreshMs )
                {
                    discovery.unregisterService(instance);
                }
            }
        }
    }
    catch ( Exception e )
    {
        ThreadUtils.checkInterrupted(e);
        log.error(String.format("GC for service: %s", name), e);
    }
}
 
Example #16
Source File: RetryLoop.java    From xian with Apache License 2.0 6 votes vote down vote up
/**
 * Convenience utility: creates a retry loop calling the given proc and retrying if needed
 *
 * @param client Zookeeper
 * @param proc procedure to call with retry
 * @param <T> return type
 * @return procedure result
 * @throws Exception any non-retriable errors
 */
public static<T> T      callWithRetry(CuratorZookeeperClient client, Callable<T> proc) throws Exception
{
    T               result = null;
    RetryLoop       retryLoop = client.newRetryLoop();
    while ( retryLoop.shouldContinue() )
    {
        try
        {
            client.internalBlockUntilConnectedOrTimedOut();

            result = proc.call();
            retryLoop.markComplete();
        }
        catch ( Exception e )
        {
            ThreadUtils.checkInterrupted(e);
            retryLoop.takeException(e);
        }
    }
    return result;
}
 
Example #17
Source File: DiscoveryResource.java    From curator with Apache License 2.0 6 votes vote down vote up
@DELETE
@Path("v1/service/{name}/{id}")
public Response     removeService(@PathParam("name") String name, @PathParam("id") String id)
{
    try
    {
        ServiceInstance<T> instance = context.getServiceDiscovery().queryForInstance(name, id);
        if ( instance != null )
        {
            //noinspection unchecked
            context.getServiceDiscovery().unregisterService(instance);
        }
    }
    catch ( Exception e )
    {
        ThreadUtils.checkInterrupted(e);
        log.error("Trying to delete service", e);
        return Response.serverError().build();
    }
    return Response.ok().build();
}
 
Example #18
Source File: CuratorZookeeperClient.java    From xian with Apache License 2.0 6 votes vote down vote up
/**
 * Close the client
 */
public void     close()
{
    log.debug("Closing");

    started.set(false);
    try
    {
        state.close();
    }
    catch ( IOException e )
    {
        ThreadUtils.checkInterrupted(e);
        log.error("", e);
    }
}
 
Example #19
Source File: ConnectionState.java    From xian with Apache License 2.0 6 votes vote down vote up
@Override
public void close() throws IOException
{
    log.debug("Closing");

    CloseableUtils.closeQuietly(ensembleProvider);
    try
    {
        zooKeeper.closeAndClear();
    }
    catch ( Exception e )
    {
        ThreadUtils.checkInterrupted(e);
        throw new IOException(e);
    }
    finally
    {
        isConnected.set(false);
    }
}
 
Example #20
Source File: ConnectionState.java    From curator with Apache License 2.0 6 votes vote down vote up
public void close(int waitForShutdownTimeoutMs) throws IOException {
    log.debug("Closing");

    CloseableUtils.closeQuietly(ensembleProvider);
    try
    {
        handleHolder.closeAndClear(waitForShutdownTimeoutMs);
    }
    catch ( Exception e )
    {
        ThreadUtils.checkInterrupted(e);
        throw new IOException(e);
    }
    finally
    {
        isConnected.set(false);
    }
}
 
Example #21
Source File: TreeCache.java    From curator with Apache License 2.0 6 votes vote down vote up
/**
 * Send an exception to any listeners, or else log the error if there are none.
 */
private void handleException(final Throwable e)
{
    if ( errorListeners.size() == 0 )
    {
        LOG.error("", e);
    }
    else
    {
        errorListeners.forEach(listener ->
        {
            try
            {
                listener.unhandledError("", e);
            }
            catch ( Exception e2 )
            {
                ThreadUtils.checkInterrupted(e2);
                LOG.error("Exception handling exception", e2);
            }
        });
    }
}
 
Example #22
Source File: TreeCache.java    From curator with Apache License 2.0 6 votes vote down vote up
/**
 * Close/end the cache.
 */
@Override
public void close()
{
    if ( treeState.compareAndSet(TreeState.STARTED, TreeState.CLOSED) )
    {
        client.removeWatchers();
        client.getConnectionStateListenable().removeListener(connectionStateListener);
        listeners.clear();
        executorService.shutdown();
        try
        {
            root.wasDeleted();
        }
        catch ( Exception e )
        {
            ThreadUtils.checkInterrupted(e);
            handleException(e);
        }
    }
}
 
Example #23
Source File: JsonServiceInstanceMarshaller.java    From curator with Apache License 2.0 6 votes vote down vote up
static<T> ObjectNode writeInstance(ObjectMapper mapper, ServiceInstance<T> instance, DiscoveryContext<T> context)
{
    ObjectNode  node = mapper.createObjectNode();
    node.put("name", instance.getName());
    node.put("id", instance.getId());
    node.put("address", instance.getAddress());
    putInteger(node, "port", instance.getPort());
    putInteger(node, "sslPort", instance.getSslPort());
    node.put("registrationTimeUTC", instance.getRegistrationTimeUTC());
    node.put("serviceType", instance.getServiceType().name());
    try
    {
        context.marshallJson(node, "payload", instance.getPayload());
    }
    catch ( Exception e )
    {
        ThreadUtils.checkInterrupted(e);
        throw new WebApplicationException(e);
    }

    return node;
}
 
Example #24
Source File: JsonServiceInstanceMarshaller.java    From curator with Apache License 2.0 5 votes vote down vote up
@Override
public ServiceInstance<T> readFrom(Class<ServiceInstance<T>> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException
{
    try
    {
        JsonNode                    node = mapper.readTree(entityStream);
        return readInstance(node, context);
    }
    catch ( Exception e )
    {
        ThreadUtils.checkInterrupted(e);
        throw new WebApplicationException(e);
    }
}
 
Example #25
Source File: SessionFailRetryLoop.java    From curator with Apache License 2.0 5 votes vote down vote up
/**
 * Convenience utility: creates a "session fail" retry loop calling the given proc
 *
 * @param client Zookeeper
 * @param mode how to handle session failures
 * @param proc procedure to call with retry
 * @param <T> return type
 * @return procedure result
 * @throws Exception any non-retriable errors
 */
public static<T> T      callWithRetry(CuratorZookeeperClient client, Mode mode, Callable<T> proc) throws Exception
{
    T                       result = null;
    SessionFailRetryLoop    retryLoop = client.newSessionFailRetryLoop(mode);
    retryLoop.start();
    try
    {
        while ( retryLoop.shouldContinue() )
        {
            try
            {
                result = proc.call();
            }
            catch ( Exception e )
            {
                ThreadUtils.checkInterrupted(e);
                retryLoop.takeException(e);
            }
        }
    }
    finally
    {
        retryLoop.close();
    }
    return result;
}
 
Example #26
Source File: DiscoveryResource.java    From curator with Apache License 2.0 5 votes vote down vote up
@PUT
@Path("v1/service/{name}/{id}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response     putService(ServiceInstance<T> instance, @PathParam("name") String name, @PathParam("id") String id)
{
    if ( !instance.getId().equals(id) || !instance.getName().equals(name) )
    {
        log.info("Request where path id and/or name doesn't match entity");
        return Response.status(Response.Status.BAD_REQUEST).build();
    }
    
    if ( instance.getServiceType().isDynamic() )
    {
        log.info("Service type cannot be dynamic");
        return Response.status(Response.Status.BAD_REQUEST).build();
    }

    try
    {
        context.getServiceDiscovery().registerService(instance);
    }
    catch ( Exception e )
    {
        ThreadUtils.checkInterrupted(e);
        log.error("Trying to register service", e);
        return Response.serverError().build();
    }

    return Response.status(Response.Status.CREATED).build();
}
 
Example #27
Source File: PathChildrenCache.java    From curator with Apache License 2.0 5 votes vote down vote up
private void handleStateChange(ConnectionState newState)
{
    switch ( newState )
    {
    case SUSPENDED:
    {
        offerOperation(new EventOperation(this, new PathChildrenCacheEvent(PathChildrenCacheEvent.Type.CONNECTION_SUSPENDED, null)));
        break;
    }

    case LOST:
    {
        offerOperation(new EventOperation(this, new PathChildrenCacheEvent(PathChildrenCacheEvent.Type.CONNECTION_LOST, null)));
        break;
    }

    case CONNECTED:
    case RECONNECTED:
    {
        try
        {
            offerOperation(new RefreshOperation(this, RefreshMode.FORCE_GET_DATA_AND_STAT));
            offerOperation(new EventOperation(this, new PathChildrenCacheEvent(PathChildrenCacheEvent.Type.CONNECTION_RECONNECTED, null)));
        }
        catch ( Exception e )
        {
            ThreadUtils.checkInterrupted(e);
            handleException(e);
        }
        break;
    }
    }
}
 
Example #28
Source File: ServiceDiscoveryImpl.java    From xian with Apache License 2.0 5 votes vote down vote up
/**
 * Allocate a new builder. {@link ServiceProviderBuilder#providerStrategy} is set to {@link RoundRobinStrategy}
 *
 * @return the builder
 */
@Override
public ServiceProviderBuilder<T> serviceProviderBuilder()
{
    return new ServiceProviderBuilderImpl<T>(this)
        .providerStrategy(new RoundRobinStrategy<T>())
        .threadFactory(ThreadUtils.newThreadFactory("ServiceProvider"));
}
 
Example #29
Source File: SharedValue.java    From curator with Apache License 2.0 5 votes vote down vote up
private void notifyListeners()
{
    final byte[] localValue = getValue();
    listeners.forEach(listener -> {
        try
        {
            listener.valueHasChanged(SharedValue.this, localValue);
        }
        catch ( Exception e )
        {
            ThreadUtils.checkInterrupted(e);
            log.error("From SharedValue listener", e);
        }
    });
}
 
Example #30
Source File: CuratorTempFrameworkImpl.java    From xian with Apache License 2.0 5 votes vote down vote up
private synchronized void openConnectionIfNeeded() throws Exception
{
    if ( client == null )
    {
        client = (CuratorFrameworkImpl)factory.build(); // cast is safe - we control both sides of this
        client.start();
    }

    if ( cleanup == null )
    {
        ThreadFactory threadFactory = factory.getThreadFactory();

        if (threadFactory == null)
        {
            threadFactory = ThreadUtils.newGenericThreadFactory("CuratorTempFrameworkImpl");
        }

        cleanup = Executors.newScheduledThreadPool(1, threadFactory);

        Runnable        command = new Runnable()
        {
            @Override
            public void run()
            {
                checkInactive();
            }
        };
        cleanup.scheduleAtFixedRate(command, inactiveThresholdMs, inactiveThresholdMs, TimeUnit.MILLISECONDS);
    }

    updateLastAccess();
}