List of usage examples for java.util.concurrent.locks Lock tryLock
boolean tryLock(long time, TimeUnit unit) throws InterruptedException;
From source file:org.grails.datastore.mapping.gemfire.engine.GemfireEntityPersister.java
@Override public Object lock(final Serializable id, final int timeout) throws CannotAcquireLockException { final GemfireTemplate template = gemfireDatastore.getTemplate(getPersistentEntity()); return template.execute(new GemfireCallback() { public Object doInGemfire(Region region) throws GemFireCheckedException, GemFireException { final Lock lock = region.getDistributedLock(id); try { if (lock.tryLock(timeout, TimeUnit.SECONDS)) { final Object o = region.get(id); distributedLocksHeld.put(o, lock); return o; }//from w ww. j a v a2 s .c om throw new CannotAcquireLockException("Timeout acquiring Gemfire lock on object type [" + getPersistentEntity() + "] with identifier [" + id + "]"); } catch (InterruptedException e) { throw new CannotAcquireLockException("Cannot acquire Gemfire lock on object type [" + getPersistentEntity() + "] with identifier [" + id + "]: " + e.getMessage(), e); } } }); }
From source file:com.esofthead.mycollab.module.project.service.ibatis.GanttAssignmentServiceImpl.java
@Override public void massUpdatePredecessors(Integer taskSourceId, final List<TaskPredecessor> predecessors, Integer sAccountId) {/*from w w w . j ava2 s. c om*/ Lock lock = DistributionLockUtil.getLock("task-service" + sAccountId); try { PredecessorMapper predecessorMapper = ApplicationContextUtil.getSpringBean(PredecessorMapper.class); PredecessorExample ex = new PredecessorExample(); ex.createCriteria().andSourceidEqualTo(taskSourceId); predecessorMapper.deleteByExample(ex); JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); final long now = new GregorianCalendar().getTimeInMillis(); if (lock.tryLock(30, TimeUnit.SECONDS)) { jdbcTemplate.batchUpdate( "INSERT INTO `m_prj_predecessor`(`sourceType`, `descType`, `predestype`,`lagDay`, " + "`sourceId`,`descId`, `createdTime`) VALUES (?, ?, ?, ?, ?, ?, ?)", new BatchPreparedStatementSetter() { @Override public void setValues(PreparedStatement preparedStatement, int i) throws SQLException { preparedStatement.setString(1, predecessors.get(i).getSourcetype()); preparedStatement.setString(2, predecessors.get(i).getDesctype()); preparedStatement.setString(3, predecessors.get(i).getPredestype()); preparedStatement.setInt(4, predecessors.get(i).getLagday()); preparedStatement.setInt(5, predecessors.get(i).getSourceid()); preparedStatement.setInt(6, predecessors.get(i).getDescid()); preparedStatement.setDate(7, new Date(now)); } @Override public int getBatchSize() { return predecessors.size(); } }); } } catch (Exception e) { throw new MyCollabException(e); } finally { DistributionLockUtil.removeLock("task-service" + sAccountId); lock.unlock(); } }
From source file:no.sesat.search.http.filters.SiteLocatorFilter.java
private static long tryLock(final HttpServletRequest request, final Deque<ServletRequest> deque, final Lock lock, long timeLeft) { final long start = System.currentTimeMillis(); try {/*w w w . jav a 2s.c o m*/ do { timeLeft = WAIT_TIME - (System.currentTimeMillis() - start); // let's sleep. sleeping too long results in 409 response if (0 >= timeLeft || !lock.tryLock(timeLeft, TimeUnit.MILLISECONDS)) { // we timed out or got the lock. waiting is over break; } else if (deque.peek() != request) { // we've acquired the lock but we're not at front of deque // release the lock and try again lock.unlock(); } } while (deque.peek() != request); } catch (InterruptedException ie) { LOG.error("Failed using user's lock", ie); } return timeLeft; }
From source file:org.apache.hadoop.hbase.regionserver.HRegion.java
/** * Try to acquire a lock. Throw RegionTooBusyException * if failed to get the lock in time. Throw InterruptedIOException * if interrupted while waiting for the lock. *///from w ww . j a v a2 s .c o m private void lock(final Lock lock, final int multiplier) throws RegionTooBusyException, InterruptedIOException { try { final long waitTime = Math.min(maxBusyWaitDuration, busyWaitDuration * Math.min(multiplier, maxBusyWaitMultiplier)); if (!lock.tryLock(waitTime, TimeUnit.MILLISECONDS)) { throw new RegionTooBusyException("failed to get a lock in " + waitTime + " ms. " + "regionName=" + (this.getRegionInfo() == null ? "unknown" : this.getRegionInfo().getRegionNameAsString()) + ", server=" + (this.getRegionServerServices() == null ? "unknown" : this.getRegionServerServices().getServerName())); } } catch (InterruptedException ie) { LOG.info("Interrupted while waiting for a lock"); InterruptedIOException iie = new InterruptedIOException(); iie.initCause(ie); throw iie; } }
From source file:org.archive.modules.recrawl.hbase.SingleHBaseTable.java
public void put(Put p) throws IOException { putCount.incrementAndGet();//from w ww . java 2 s .co m // trigger reconnection if necessary. as table can be modified before // read lock is acquired, we don't read table variable here. getTable(); boolean htableFailed = false; HTableInterface htable = null; Lock readLock = tableUseLock.readLock(); try { if (!readLock.tryLock(TRY_READ_LOCK_TIMEOUT, TimeUnit.SECONDS)) { putSkipCount.incrementAndGet(); throw new IOException("could not acquire read lock for HTable."); } } catch (InterruptedException ex) { throw new IOException("interrupted while acquiring read lock", ex); } try { htable = table; if (htable == null) { putSkipCount.incrementAndGet(); throw new IOException("HBase connection is unvailable."); } // HTable.put() buffers Puts and access to the buffer is not // synchronized. synchronized (htable) { try { htable.put(p); } catch (NullPointerException ex) { // HTable.put() throws NullPointerException when connection is lost. // It is somewhat weird, so translate it to IOException. putErrorCount.incrementAndGet(); htableFailed = true; throw new IOException("hbase connection is lost", ex); } catch (NotServingRegionException ex) { putErrorCount.incrementAndGet(); // no need to close HTable. throw ex; } catch (IOException ex) { putErrorCount.incrementAndGet(); htableFailed = true; throw ex; } } } finally { readLock.unlock(); if (htableFailed) { closeTable(htable, true); } } }
From source file:org.archive.modules.recrawl.hbase.SingleHBaseTable.java
public Result get(Get g) throws IOException { getCount.incrementAndGet();// w ww . ja va 2 s . com // trigger reconnection if necessary. as table can be modified before // read lock is acquired, we don't read table variable here. getTable(); boolean htableFailed = false; HTableInterface htable = null; Lock readLock = tableUseLock.readLock(); try { if (!readLock.tryLock(TRY_READ_LOCK_TIMEOUT, TimeUnit.SECONDS)) { getSkipCount.incrementAndGet(); throw new IOException("could not acquire read lock for HTable."); } } catch (InterruptedException ex) { throw new IOException("interrupted while acquiring read lock", ex); } try { htable = table; if (htable == null) { getSkipCount.incrementAndGet(); throw new IOException("HBase connection is unvailable."); } try { return htable.get(g); } catch (NotServingRegionException ex) { // caused by disruption to HBase cluster. no need to // refresh HBase connection, since connection itself // is working okay. // TODO: should we need to back-off for a while? other // regions may still be accessible. getErrorCount.incrementAndGet(); throw ex; } catch (IOException ex) { getErrorCount.incrementAndGet(); htableFailed = true; throw ex; } } finally { readLock.unlock(); if (htableFailed) { closeTable(htable, true); } } }
From source file:org.archive.modules.recrawl.hbase.SingleHBaseTable.java
/** * close current connection and establish new connection. * fails silently if back-off period is in effect. *//*w w w . j a v a2 s.c om*/ protected void reconnect(boolean onerror) throws IOException, InterruptedException { // avoid deadlock situation caused by attempting // to acquire write lock while holding read lock. // there'd be no real dead-lock now that timeout on write lock is implemented, // but it's nice to know there's a bug in locking. if (tableUseLock.getReadHoldCount() > 0) { LOG.warn("avoiding deadlock: reconnect() called by thread with read lock."); return; } Lock writeLock = tableUseLock.writeLock(); if (!writeLock.tryLock(TRY_WRITE_LOCK_TIMEOUT, TimeUnit.SECONDS)) { LOG.warn("reconnect() could not acquire write lock on tableUseLock for " + TRY_WRITE_LOCK_TIMEOUT + "s, giving up."); return; } try { closeTable(table, onerror); openTable(); } finally { writeLock.unlock(); } }
From source file:org.nuxeo.ecm.platform.web.common.requestcontroller.filter.NuxeoRequestControllerFilter.java
/** * Synchronizes the HttpSession./*from w ww . j a v a 2 s . c o m*/ * <p> * Uses a {@link Lock} object in the HttpSession and locks it. If HttpSession is not created, exits without locking * anything. */ public static boolean simpleSyncOnSession(HttpServletRequest request) { HttpSession session = request.getSession(false); if (session == null) { if (log.isDebugEnabled()) { log.debug(doFormatLogMessage(request, "HttpSession does not exist, this request won't be synched")); } return false; } if (log.isDebugEnabled()) { log.debug(doFormatLogMessage(request, "Trying to sync on session ")); } if (request.getAttribute(SYNCED_REQUEST_FLAG) != null) { if (log.isWarnEnabled()) { log.warn(doFormatLogMessage(request, "Request has already be synced, filter is reentrant, exiting without locking")); } return false; } Lock lock = (Lock) session.getAttribute(SESSION_LOCK_KEY); if (lock == null) { lock = new ReentrantLock(); session.setAttribute(SESSION_LOCK_KEY, lock); } boolean locked = false; try { locked = lock.tryLock(LOCK_TIMOUT_S, TimeUnit.SECONDS); } catch (InterruptedException e) { log.error(doFormatLogMessage(request, "Unable to acquire lock for Session sync"), e); return false; } if (locked) { request.setAttribute(SYNCED_REQUEST_FLAG, true); if (log.isDebugEnabled()) { log.debug(doFormatLogMessage(request, "Request synced on session")); } } else { if (log.isDebugEnabled()) { log.debug(doFormatLogMessage(request, "Sync timeout")); } } return locked; }
From source file:org.nuxeo.ecm.platform.wi.filter.WIRequestFilter.java
protected boolean simpleSyncOnSession(HttpServletRequest request) { if (log.isDebugEnabled()) { log.debug(doFormatLogMessage(request, "Trying to sync on session ")); }/*from w w w .j a v a 2 s .co m*/ if (request.getAttribute(SYNCED_REQUEST_FLAG) != null) { if (log.isWarnEnabled()) { log.warn(doFormatLogMessage(request, "Request has already be synced, filter is reentrant, exiting without locking")); } return false; } WISession session = (WISession) request.getAttribute(SESSION_KEY); Lock lock = (Lock) session.getAttribute(SESSION_LOCK_KEY); if (lock == null) { lock = new ReentrantLock(); session.setAttribute(SESSION_LOCK_KEY, lock); } boolean locked = false; try { locked = lock.tryLock(LOCK_TIMOUT_S, TimeUnit.SECONDS); } catch (InterruptedException e) { log.error(doFormatLogMessage(request, "Unable to acuire lock for Session sync"), e); return false; } if (locked) { request.setAttribute(SYNCED_REQUEST_FLAG, Boolean.TRUE); request.setAttribute(SESSION_LOCK_TIME, Long.valueOf(System.currentTimeMillis())); if (log.isDebugEnabled()) { log.debug(doFormatLogMessage(request, "Request synced on session")); } } else { if (log.isDebugEnabled()) { log.debug(doFormatLogMessage(request, "Sync timeout")); } } return locked; }