Example usage for java.util.concurrent.locks ReadWriteLock writeLock

List of usage examples for java.util.concurrent.locks ReadWriteLock writeLock

Introduction

In this page you can find the example usage for java.util.concurrent.locks ReadWriteLock writeLock.

Prototype

Lock writeLock();

Source Link

Document

Returns the lock used for writing.

Usage

From source file:org.hsweb.web.datasource.dynamic.DynamicDataSourceServiceImpl.java

protected CacheInfo getCache(String id) {
    DynamicDataSource.useDefault();//  ww  w.jav a2  s .  c  o  m
    try {
        DataSource old = dataSourceService.selectByPk(id);
        if (old == null || old.getEnabled() != 1)
            throw new NotFoundException("????");

        //?
        ReadWriteLock readWriteLock = lockFactory.createReadWriteLock("dynamic.ds." + id);

        readWriteLock.readLock().tryLock();
        CacheInfo cacheInfo = null;
        try {
            cacheInfo = cache.get(id);
            // ,hash
            if (cacheInfo != null && cacheInfo.getHash() == old.getHash())
                return cacheInfo;
        } finally {
            try {
                readWriteLock.readLock().unlock();
            } catch (Exception e) {
            }
        }
        readWriteLock.writeLock().tryLock();
        try {
            if (cacheInfo != null) {
                closeDataSource(cacheInfo.getDataSource());
            }
            //datasource
            javax.sql.DataSource dataSource = createDataSource(old);
            cacheInfo = new CacheInfo(old.getHash(), dataSource);
            cache.put(id, cacheInfo);
        } finally {
            try {
                readWriteLock.writeLock().unlock();
            } catch (Exception e) {
            }
        }
        return cacheInfo;
    } finally {
        DynamicDataSource.useLast();
    }
}

From source file:org.apache.hadoop.crypto.key.JavaKeyStoreProvider.java

private JavaKeyStoreProvider(URI uri, Configuration conf) throws IOException {
    super(conf);//from  www.j  a va 2 s .c  o m
    this.uri = uri;
    path = ProviderUtils.unnestUri(uri);
    fs = path.getFileSystem(conf);
    // Get the password file from the conf, if not present from the user's
    // environment var
    if (System.getenv().containsKey(KEYSTORE_PASSWORD_ENV_VAR)) {
        password = System.getenv(KEYSTORE_PASSWORD_ENV_VAR).toCharArray();
    }
    if (password == null) {
        String pwFile = conf.get(KEYSTORE_PASSWORD_FILE_KEY);
        if (pwFile != null) {
            ClassLoader cl = Thread.currentThread().getContextClassLoader();
            URL pwdFile = cl.getResource(pwFile);
            if (pwdFile == null) {
                // Provided Password file does not exist
                throw new IOException("Password file does not exists");
            }
            try (InputStream is = pwdFile.openStream()) {
                password = IOUtils.toString(is).trim().toCharArray();
            }
        }
    }
    if (password == null) {
        password = KEYSTORE_PASSWORD_DEFAULT;
    }
    try {
        Path oldPath = constructOldPath(path);
        Path newPath = constructNewPath(path);
        keyStore = KeyStore.getInstance(SCHEME_NAME);
        FsPermission perm = null;
        if (fs.exists(path)) {
            // flush did not proceed to completion
            // _NEW should not exist
            if (fs.exists(newPath)) {
                throw new IOException(String.format("Keystore not loaded due to some inconsistency "
                        + "('%s' and '%s' should not exist together)!!", path, newPath));
            }
            perm = tryLoadFromPath(path, oldPath);
        } else {
            perm = tryLoadIncompleteFlush(oldPath, newPath);
        }
        // Need to save off permissions in case we need to
        // rewrite the keystore in flush()
        permissions = perm;
    } catch (KeyStoreException e) {
        throw new IOException("Can't create keystore", e);
    } catch (NoSuchAlgorithmException e) {
        throw new IOException("Can't load keystore " + path, e);
    } catch (CertificateException e) {
        throw new IOException("Can't load keystore " + path, e);
    }
    ReadWriteLock lock = new ReentrantReadWriteLock(true);
    readLock = lock.readLock();
    writeLock = lock.writeLock();
}

From source file:org.apache.tajo.master.querymaster.Query.java

public Query(final QueryMasterTask.QueryMasterTaskContext context, final QueryId id, final long appSubmitTime,
        final String queryStr, final EventHandler eventHandler, final MasterPlan plan) {
    this.context = context;
    this.systemConf = context.getConf();
    this.id = id;
    this.clock = context.getClock();
    this.appSubmitTime = appSubmitTime;
    this.queryStr = queryStr;
    this.stages = Maps.newConcurrentMap();
    this.eventHandler = eventHandler;
    this.plan = plan;
    this.cursor = new ExecutionBlockCursor(plan, true);

    StringBuilder sb = new StringBuilder("\n=======================================================");
    sb.append("\nThe order of execution: \n");
    int order = 1;
    while (cursor.hasNext()) {
        ExecutionBlock currentEB = cursor.nextBlock();
        sb.append("\n").append(order).append(": ").append(currentEB.getId());
        order++;// w w w.j a  va 2 s.co m
    }
    sb.append("\n=======================================================");
    LOG.info(sb);
    cursor.reset();

    ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    this.readLock = readWriteLock.readLock();
    this.writeLock = readWriteLock.writeLock();

    stateMachine = stateMachineFactory.make(this);
    queryState = stateMachine.getCurrentState();
}

From source file:org.apache.tajo.master.SubQuery.java

public SubQuery(QueryContext context, ExecutionBlock block, StorageManager sm) {
    this.context = context;
    this.block = block;
    this.sm = sm;
    this.eventHandler = context.getEventHandler();

    ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    this.readLock = readWriteLock.readLock();
    this.writeLock = readWriteLock.writeLock();
    stateMachine = stateMachineFactory.make(this);
}

From source file:net.myrrix.online.ServerRecommender.java

private static float[] getFeatures(long id, FastByIDMap<float[]> matrix, ReadWriteLock lock) {
    float[] features;
    Lock readLock = lock.readLock();
    readLock.lock();//from   w  ww .  jav a 2s .c o m
    try {
        features = matrix.get(id);
        if (features == null) {
            int numFeatures = countFeatures(matrix);
            if (numFeatures > 0) {
                features = new float[numFeatures];
                Lock writeLock = lock.writeLock();
                readLock.unlock();
                writeLock.lock();
                try {
                    matrix.put(id, features);
                } finally {
                    readLock.lock();
                    writeLock.unlock();
                }
            }
        }
    } finally {
        readLock.unlock();
    }
    return features;
}

From source file:org.apache.tajo.master.querymaster.QueryUnit.java

public QueryUnit(Configuration conf, QueryUnitAttemptScheduleContext scheduleContext, QueryUnitId id,
        boolean isLeafTask, EventHandler eventHandler) {
    this.systemConf = conf;
    this.taskId = id;
    this.eventHandler = eventHandler;
    this.isLeafTask = isLeafTask;
    scan = new ArrayList<ScanNode>();
    fetchMap = Maps.newHashMap();//from  w  w w .  j  a v  a  2s . com
    fragMap = Maps.newHashMap();
    shuffleFileOutputs = new ArrayList<ShuffleFileOutput>();
    attempts = Collections.emptyMap();
    lastAttemptId = null;
    nextAttempt = -1;
    failedAttempts = 0;

    ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    this.readLock = readWriteLock.readLock();
    this.writeLock = readWriteLock.writeLock();
    this.scheduleContext = scheduleContext;

    stateMachine = stateMachineFactory.make(this);
    totalFragmentNum = 0;
}

From source file:org.apache.tajo.querymaster.Task.java

public Task(Configuration conf, TaskAttemptScheduleContext scheduleContext, TaskId id, boolean isLeafTask,
        EventHandler eventHandler) {
    this.systemConf = conf;
    this.taskId = id;
    this.eventHandler = eventHandler;
    this.isLeafTask = isLeafTask;
    scan = new ArrayList<>();
    fetchMap = Maps.newHashMap();// w  w  w .  j ava  2s.  c  o m
    fragMap = Maps.newHashMap();
    shuffleFileOutputs = new ArrayList<>();
    attempts = Collections.emptyMap();
    lastAttemptId = null;
    nextAttempt = -1;
    failedAttempts = 0;

    ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    this.readLock = readWriteLock.readLock();
    this.writeLock = readWriteLock.writeLock();
    this.scheduleContext = scheduleContext;

    stateMachine = stateMachineFactory.make(this);
    totalFragmentNum = 0;
    maxUrlLength = conf.getInt(ConfVars.PULLSERVER_FETCH_URL_MAX_LENGTH.name(),
            ConfVars.PULLSERVER_FETCH_URL_MAX_LENGTH.defaultIntVal);
}

From source file:org.apache.tajo.master.querymaster.Task.java

public Task(Configuration conf, TaskAttemptScheduleContext scheduleContext, TaskId id, boolean isLeafTask,
        EventHandler eventHandler) {
    this.systemConf = conf;
    this.taskId = id;
    this.eventHandler = eventHandler;
    this.isLeafTask = isLeafTask;
    scan = new ArrayList<ScanNode>();
    fetchMap = Maps.newHashMap();/*from ww w  . j av a  2  s  .co  m*/
    fragMap = Maps.newHashMap();
    shuffleFileOutputs = new ArrayList<ShuffleFileOutput>();
    attempts = Collections.emptyMap();
    lastAttemptId = null;
    nextAttempt = -1;
    failedAttempts = 0;

    ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    this.readLock = readWriteLock.readLock();
    this.writeLock = readWriteLock.writeLock();
    this.scheduleContext = scheduleContext;

    stateMachine = stateMachineFactory.make(this);
    totalFragmentNum = 0;
}

From source file:org.nabucco.alfresco.enhScriptEnv.common.webscripts.processor.EnhancedJSScriptProcessor.java

protected void updateScriptCache(final Map<String, Script> cache, final ReadWriteLock lock, final String key,
        final Script script) {
    lock.writeLock().lock();
    try {//from   ww w .j  a  v a2  s .com
        cache.put(key, script);

        if (cache.size() > this.maxScriptCacheSize) {
            final Iterator<String> keyIterator = cache.keySet().iterator();
            while (cache.size() > this.maxScriptCacheSize) {
                final String keyToRemove = keyIterator.next();
                cache.remove(keyToRemove);
            }
        }
    } finally {
        lock.writeLock().unlock();
    }
}

From source file:org.eclipse.orion.internal.server.core.metastore.SimpleMetaStoreV1.java

public void deleteUser(String userId) throws CoreException {
    ReadWriteLock lock = getLockForUser(userId);
    lock.writeLock().lock();
    try {//from   ww w.  j a va2 s  .co m
        UserInfo userInfo;
        try {
            userInfo = readUser(userId);
        } catch (CoreException exception) {
            throw new CoreException(new Status(IStatus.ERROR, ServerConstants.PI_SERVER_CORE, 1,
                    "SimpleMetaStore.deleteUser: could not delete user with id: " + userId
                            + ", user does not exist.",
                    null));
        }

        // First delete the workspaces
        for (String workspaceId : userInfo.getWorkspaceIds()) {
            deleteWorkspace(userId, workspaceId);
        }

        File userMetaFolder = SimpleMetaStoreUtil.readMetaUserFolder(getRootLocation(), userId);
        if (!SimpleMetaStoreUtil.deleteMetaFile(userMetaFolder, SimpleMetaStore.USER)) {
            throw new CoreException(new Status(IStatus.ERROR, ServerConstants.PI_SERVER_CORE, 1,
                    "SimpleMetaStore.deleteUser: could not delete user: " + userId, null));
        }
        if (!SimpleMetaStoreUtil.deleteMetaUserFolder(userMetaFolder, userId)) {
            throw new CoreException(new Status(IStatus.ERROR, ServerConstants.PI_SERVER_CORE, 1,
                    "SimpleMetaStore.deleteUser: could not delete user: " + userId, null));
        }
    } finally {
        lock.writeLock().unlock();
    }
}