Example usage for java.util.concurrent.locks ReentrantLock lock

List of usage examples for java.util.concurrent.locks ReentrantLock lock

Introduction

In this page you can find the example usage for java.util.concurrent.locks ReentrantLock lock.

Prototype

public void lock() 

Source Link

Document

Acquires the lock.

Usage

From source file:ir.rasen.charsoo.controller.image_loader.core.LoadAndDisplayImageTask.java

@Override
public void run() {
    if (waitIfPaused())
        return;//from  w w w  . j  a  v  a 2 s .  c  om
    if (delayIfNeed())
        return;

    ReentrantLock loadFromUriLock = imageLoadingInfo.loadFromUriLock;
    L.d(LOG_START_DISPLAY_IMAGE_TASK, memoryCacheKey);
    if (loadFromUriLock.isLocked()) {
        L.d(LOG_WAITING_FOR_IMAGE_LOADED, memoryCacheKey);
    }

    loadFromUriLock.lock();
    Bitmap bmp;
    try {
        checkTaskNotActual();

        bmp = configuration.memoryCache.get(memoryCacheKey);
        if (bmp == null || bmp.isRecycled()) {
            bmp = tryLoadBitmap();
            if (bmp == null)
                return; // listener callback already was fired

            checkTaskNotActual();
            checkTaskInterrupted();

            if (options.shouldPreProcess()) {
                L.d(LOG_PREPROCESS_IMAGE, memoryCacheKey);
                bmp = options.getPreProcessor().process(bmp);
                if (bmp == null) {
                    L.e(ERROR_PRE_PROCESSOR_NULL, memoryCacheKey);
                }
            }

            if (bmp != null && options.isCacheInMemory()) {
                L.d(LOG_CACHE_IMAGE_IN_MEMORY, memoryCacheKey);
                configuration.memoryCache.put(memoryCacheKey, bmp);
            }
        } else {
            loadedFrom = LoadedFrom.MEMORY_CACHE;
            L.d(LOG_GET_IMAGE_FROM_MEMORY_CACHE_AFTER_WAITING, memoryCacheKey);
        }

        if (bmp != null && options.shouldPostProcess()) {
            L.d(LOG_POSTPROCESS_IMAGE, memoryCacheKey);
            bmp = options.getPostProcessor().process(bmp);
            if (bmp == null) {
                L.e(ERROR_POST_PROCESSOR_NULL, memoryCacheKey);
            }
        }
        checkTaskNotActual();
        checkTaskInterrupted();
    } catch (TaskCancelledException e) {
        fireCancelEvent();
        return;
    } finally {
        loadFromUriLock.unlock();
    }

    DisplayBitmapTask displayBitmapTask = new DisplayBitmapTask(bmp, imageLoadingInfo, engine, loadedFrom);
    runTask(displayBitmapTask, syncLoading, handler, engine);
}

From source file:org.openspaces.persistency.cassandra.HectorCassandraClient.java

/**
 * Adds a secondary index to the provided columns in the column family matching the provided
 * typeName. Creates the column if it does not already exist.
 *
 * @param typeName    The type name describing the matchin column family.
 * @param columnNames the columns to which secondary indexes should be added.
 *//*from ww  w  .  ja va2 s.  com*/
public void addIndexesToColumnFamily(String typeName, List<String> columnNames,
        SpaceDocumentColumnFamilyMapper mapper) {
    ColumnFamilyMetadata metadata = metadataCache.getColumnFamilyMetadata(typeName);
    if (metadata == null) {
        metadata = fetchColumnFamilyMetadata(typeName, mapper);
        if (metadata == null) {
            throw new SpaceCassandraSchemaUpdateException(
                    "Failed finding column family metadata for " + typeName, null, false);
        }
    }

    ReentrantLock lockForType = namedLock.forName(metadata.getTypeName());
    lockForType.lock();
    try {
        metadata.getIndexes().addAll(columnNames);

        ColumnFamilyDefinition columnFamilyDefinition = getColumnFamilyDefinition(metadata);
        if (columnFamilyDefinition == null) {
            throw new SpaceCassandraSchemaUpdateException("column family definition: "
                    + metadata.getColumnFamilyName() + " for type: " + typeName + " not found", null, false);
        }

        ThriftCfDef thriftCfDef = new ThriftCfDef(columnFamilyDefinition);
        for (String columnName : columnNames) {

            ByteBuffer serializedColumnName = StringSerializer.get().toByteBuffer(columnName);
            ColumnDefinition originalColumnDefinition = getColumnDefinition(serializedColumnName, thriftCfDef);

            if (originalColumnDefinition == null) {
                String validationClass = ValidatorClassInferer.getBytesTypeValidationClass();
                addColumnDefinitionToColumnFamilyDefinition(metadata, thriftCfDef, columnName, validationClass);
            } else if (originalColumnDefinition.getIndexName() != null) {
                // index already exists for this column, no need to proceed
                continue;
            } else {
                List<ColumnDefinition> currentColumns = thriftCfDef.getColumnMetadata();
                thriftCfDef.setColumnMetadata(new ArrayList<ColumnDefinition>());
                BasicColumnDefinition replacedColumnDefinition = new BasicColumnDefinition();
                replacedColumnDefinition.setName(originalColumnDefinition.getName());
                replacedColumnDefinition.setValidationClass(originalColumnDefinition.getValidationClass());
                replacedColumnDefinition.setIndexName(generateIndexName(typeName, columnName));
                replacedColumnDefinition.setIndexType(ColumnIndexType.KEYS);

                for (ColumnDefinition columnDef : currentColumns) {
                    if (columnDef != originalColumnDefinition) {
                        thriftCfDef.addColumnDefinition(columnDef);
                    } else {
                        thriftCfDef.addColumnDefinition(replacedColumnDefinition);
                    }
                }
            }
        }

        if (logger.isInfoEnabled()) {
            logger.info("Adding indexes to columns: " + columnNames + " of type: " + metadata.getTypeName()
                    + ", column family: " + metadata.getColumnFamilyName());
        }

        try {
            cluster.updateColumnFamily(thriftCfDef, true);
        } catch (Exception e) {
            throw new SpaceCassandraSchemaUpdateException("Failed adding column family definition to cassandra",
                    null, true);
        }

    } finally {
        lockForType.unlock();
    }
}

From source file:org.openspaces.persistency.cassandra.HectorCassandraClient.java

/**
 * Creates a column family on the configured keyspace if one does not already exist.
 *
 * @param metadata      The metadata describing the column family to create.
 * @param shouldPersist Should the {@link ColumnFamilyMetadata} instance be persisted to the
 *                      internal metadata column family.
 *//* w  ww  . j a v  a2  s.c  om*/
public void createColumnFamilyIfNecessary(ColumnFamilyMetadata metadata, boolean shouldPersist) {

    ReentrantLock lockForType = namedLock.forName(metadata.getTypeName());
    lockForType.lock();
    try {

        final boolean columnFamilyExists = isColumnFamilyExists(metadata);

        if (columnFamilyExists) {
            if (metadata != ColumnFamilyMetadataMetadata.INSTANCE) {
                metadataCache.addColumnFamilyMetadata(metadata.getTypeName(), metadata);
                // we persist the metadata again here, because it is possible
                // that the table creation was successful but writing the internal metadata
                // failed. without this, we will never write the internal metadata.
                // the assumption here is that we write the exact same metadata.
                if (shouldPersist) {
                    persistColumnFamilyMetadata(metadata);
                }
            }
            return;
        }

        ThriftCfDef cfDef = (ThriftCfDef) HFactory.createColumnFamilyDefinition(keyspace.getKeyspaceName(),
                metadata.getColumnFamilyName());
        cfDef.setColumnMetadata(new ArrayList<ColumnDefinition>());
        cfDef.setDefaultValidationClass(ValidatorClassInferer.getBytesTypeValidationClass());
        cfDef.setComparatorType(StringSerializer.get().getComparatorType());
        cfDef.setKeyAlias(StringSerializer.get().toByteBuffer(metadata.getKeyName()));
        cfDef.setKeyValidationClass(ValidatorClassInferer.infer(metadata.getKeyType()));
        cfDef.setComment(metadata.getTypeName());

        if (columnFamilyGcGraceSeconds != null) {
            cfDef.setGcGraceSeconds(columnFamilyGcGraceSeconds);
        }

        for (TypedColumnMetadata columnMetadata : metadata.getColumns().values()) {
            String validationClass = ValidatorClassInferer.infer(columnMetadata.getType());
            addColumnDefinitionToColumnFamilyDefinition(metadata, cfDef, columnMetadata.getFullName(),
                    validationClass);
        }

        // create stub columns for statically defined indexes of dynamic properties
        for (String index : metadata.getIndexes()) {
            // we took care of these in the previous for loop
            if (metadata.getColumns().containsKey(index)) {
                continue;
            }

            String validationClass = ValidatorClassInferer.getBytesTypeValidationClass();
            addColumnDefinitionToColumnFamilyDefinition(metadata, cfDef, index, validationClass);
        }

        if (logger.isInfoEnabled()) {
            logger.info("Creating column family: " + metadata);
        }

        try {
            // first create the actual column family
            try {
                cluster.addColumnFamily(cfDef, true);
            } catch (Exception e) {
                // This could be due to current type introduction
                // If column family already exists, we can ignore this exception, otherwise we propage
                if (logger.isInfoEnabled()) {
                    logger.info("Column family creation failed, " + "waiting " + (SLEEP_BEFORE_RETRY / 1000)
                            + " seconds and then testing to see whether "
                            + "the column family was already created.", e);
                }
                Thread.sleep(SLEEP_BEFORE_RETRY);
                if (!isColumnFamilyExists(metadata)) {
                    throw e;
                }
            }

            if (metadata != ColumnFamilyMetadataMetadata.INSTANCE) {
                metadataCache.addColumnFamilyMetadata(metadata.getTypeName(), metadata);
                if (shouldPersist) {
                    persistColumnFamilyMetadata(metadata);
                }
            }

        } catch (Exception e) {
            throw new SpaceCassandraSchemaUpdateException("Failed adding column family definition to cassandra",
                    e, true);
        }
    } finally {
        lockForType.unlock();
    }
}

From source file:edu.brown.cs.systems.retro.throttling.throttlingqueues.ThrottlingLockingQueue.java

public int size() {
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {//from   w ww . j a va 2 s . c  o m
        return size;
    } finally {
        lock.unlock();
    }
}

From source file:edu.brown.cs.systems.retro.throttling.throttlingqueues.ThrottlingLockingQueue.java

public void setRate(int tenantId, double rate) {
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {//from  ww  w.  j  ava 2s .co  m
        queue(tenantId).setRate(rate);
    } finally {
        lock.unlock();
    }
}

From source file:edu.brown.cs.systems.retro.throttling.throttlingqueues.ThrottlingLockingQueue.java

public void clearRate(int tenantId) {
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {/*w  ww. j  a v  a 2 s . c om*/
        queue(tenantId).clearRate();
    } finally {
        lock.unlock();
    }
}

From source file:edu.brown.cs.systems.retro.throttling.throttlingqueues.ThrottlingLockingQueue.java

/**
 * Retrieves, but does not remove, the head of this queue, or returns
 * <tt>null</tt> if this queue is empty. Unlike <tt>poll</tt>, if no expired
 * elements are available in the queue, this method returns the element that
 * will expire next, if one exists.//from   w  w  w  . j a  va  2 s  . c  om
 *
 * @return the head of this queue, or <tt>null</tt> if this queue is empty.
 */
public E peek() {
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
        return peekNext(now());
    } finally {
        lock.unlock();
    }
}

From source file:edu.brown.cs.systems.retro.throttling.throttlingqueues.ThrottlingLockingQueue.java

/**
 * Returns an array containing all of the elements in this queue; the
 * runtime type of the returned array is that of the specified array. The
 * returned array elements are in no particular order. If the queue fits in
 * the specified array, it is returned therein. Otherwise, a new array is
 * allocated with the runtime type of the specified array and the size of
 * this queue./*from  w  w w . j ava  2 s .  c  o  m*/
 *
 * <p>
 * If this queue fits in the specified array with room to spare (i.e., the
 * array has more elements than this queue), the element in the array
 * immediately following the end of the queue is set to <tt>null</tt>.
 *
 * <p>
 * Like the {@link #toArray()} method, this method acts as bridge between
 * array-based and collection-based APIs. Further, this method allows
 * precise control over the runtime type of the output array, and may, under
 * certain circumstances, be used to save allocation costs.
 *
 * <p>
 * The following code can be used to dump a delay queue into a newly
 * allocated array of <tt>Delayed</tt>:
 *
 * <pre>
 * Delayed[] a = q.toArray(new Delayed[0]);
 * </pre>
 *
 * Note that <tt>toArray(new Object[0])</tt> is identical in function to
 * <tt>toArray()</tt>.
 *
 * @param a
 *            the array into which the elements of the queue are to be
 *            stored, if it is big enough; otherwise, a new array of the
 *            same runtime type is allocated for this purpose
 * @return an array containing all of the elements in this queue
 * @throws ArrayStoreException
 *             if the runtime type of the specified array is not a supertype
 *             of the runtime type of every element in this queue
 * @throws NullPointerException
 *             if the specified array is null
 */
public <T> T[] toArray(T[] a) {
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
        return (T[]) toArray(a);
    } finally {
        lock.unlock();
    }
}

From source file:edu.brown.cs.systems.retro.throttling.throttlingqueues.ThrottlingLockingQueue.java

/**
 * Atomically removes all of the elements from this delay queue. The queue
 * will be empty after this call returns. Elements with an unexpired delay
 * are not waited for; they are simply discarded from the queue.
 *//*from  www  .jav  a 2  s.  c o m*/
public void clear() {
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
        for (TenantQueue q : qs.values()) {
            q.clear();
        }
    } finally {
        lock.unlock();
    }
}

From source file:edu.brown.cs.systems.retro.throttling.throttlingqueues.ThrottlingLockingQueue.java

@Override
public void clearRates() {
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {//www  .  j a  v  a  2 s . c  om
        for (TenantQueue q : qs.values()) {
            q.clearRate();
        }
    } finally {
        lock.unlock();
    }
}