List of usage examples for javax.persistence LockModeType PESSIMISTIC_WRITE
LockModeType PESSIMISTIC_WRITE
To view the source code for javax.persistence LockModeType PESSIMISTIC_WRITE.
Click Source Link
From source file:com.pinterest.rocksplicator.controller.mysql.MySQLTaskQueue.java
@Override public int resetZombieTasks(final int zombieThresholdSeconds) { beginTransaction();// w w w. j a v a2 s . co m List<TaskEntity> runningTasks = getEntityManager().createNamedQuery("task.peekTasksWithState") .setParameter("state", TaskState.RUNNING.intValue()).setLockMode(LockModeType.PESSIMISTIC_WRITE) .getResultList(); List<TaskEntity> zombieTasks = runningTasks.stream() .filter(t -> t.getState() == TaskState.RUNNING.intValue() && DateUtils.addSeconds(t.getLastAliveAt(), zombieThresholdSeconds).before(new Date())) .collect(Collectors.toList()); for (TaskEntity zombieTask : zombieTasks) { getEntityManager().lock(zombieTask.getCluster(), LockModeType.PESSIMISTIC_WRITE); zombieTask.setState(TaskState.PENDING.intValue()); zombieTask.getCluster().setLocks(0); getEntityManager().persist(zombieTask); getEntityManager().persist(zombieTask.getCluster()); } getEntityManager().getTransaction().commit(); return zombieTasks.size(); }
From source file:org.ibankapp.base.persistence.repository.test.JpaRepositoryTest.java
@Test @Transactional/* w ww . java 2 s . co m*/ public void testFindAllFull() { persistThree(); Map<String, Object> hints = new HashMap<>(); hints.put("org.hibernate.comment", "test hints"); List<SimpleModel> models = repository.findAll(SimpleModel.class, null, null, LockModeType.PESSIMISTIC_WRITE, hints); Assert.assertEquals(3, models.size()); hints = new HashMap<>(); models = repository.findAll(SimpleModel.class, null, null, LockModeType.PESSIMISTIC_WRITE, hints); Assert.assertEquals(3, models.size()); }
From source file:net.groupbuy.dao.impl.OrderDaoImpl.java
public void releaseStock() { String jpql = "select orders from Order orders where orders.isAllocatedStock = :isAllocatedStock and orders.expire is not null and orders.expire <= :now"; List<Order> orders = entityManager.createQuery(jpql, Order.class).setParameter("isAllocatedStock", true) .setParameter("now", new Date()).getResultList(); if (orders != null) { for (Order order : orders) { if (order != null && order.getOrderItems() != null) { for (OrderItem orderItem : order.getOrderItems()) { if (orderItem != null) { Product product = orderItem.getProduct(); if (product != null) { entityManager.lock(product, LockModeType.PESSIMISTIC_WRITE); product.setAllocatedStock(product.getAllocatedStock() - (orderItem.getQuantity() - orderItem.getShippedQuantity())); }//from ww w. j a v a2 s . co m } } order.setIsAllocatedStock(false); } } } }
From source file:gov.osti.services.Metadata.java
/** * Obtain a reserved DOI value if possible. * * @return a DoiReservation if successful, or null if not *//*from w ww . java2 s . com*/ private static DoiReservation getReservedDoi() { EntityManager em = DoeServletContextListener.createEntityManager(); // set a LOCK TIMEOUT to prevent collision em.setProperty("javax.persistence.lock.timeout", 5000); try { em.getTransaction().begin(); DoiReservation reservation = em.find(DoiReservation.class, DoiReservation.TYPE, LockModeType.PESSIMISTIC_WRITE); if (null == reservation) reservation = new DoiReservation(); reservation.reserve(); em.merge(reservation); em.getTransaction().commit(); // send it back return reservation; } catch (PessimisticLockException | LockTimeoutException e) { log.warn("DOI Reservation, unable to obtain lock.", e); return null; } finally { em.close(); } }
From source file:com.enioka.jqm.tools.JqmEngine.java
synchronized void checkEngineEnd() { jqmlogger.trace("Checking if engine should end with the latest poller"); for (QueuePoller poller : pollers.values()) { if (poller.isRunning()) { jqmlogger.trace("At least the poller on queue " + poller.getQueue().getName() + " is still running and prevents shutdown"); return; }//from ww w.j a va 2 s .c o m } if (hasEnded) { return; } jqmlogger.trace("The engine should end with the latest poller"); hasEnded = true; // If here, all pollers are down. Stop Jetty too this.server.stop(); // Also stop the internal poller this.intPoller.stop(); // Reset the stop counter - we may want to restart one day EntityManager em = null; try { em = Helpers.getNewEm(); em.getTransaction().begin(); this.node = em.find(Node.class, this.node.getId(), LockModeType.PESSIMISTIC_WRITE); this.node.setStop(false); this.node.setLastSeenAlive(null); em.getTransaction().commit(); } catch (Exception e) { // Shutdown exception is ignored (happens during tests) } finally { Helpers.closeQuietly(em); } // JMX if (loadJmxBeans) { try { MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); mbs.unregisterMBean(name); jqmlogger.trace("unregistered bean " + name); } catch (Exception e) { jqmlogger.error("Could not unregister engine JMX bean", e); } } // Note: if present, the JMX listener is not stopped as it is JVM-global, like the JNDI context // Done this.ended.release(); jqmlogger.info("JQM engine has stopped"); }
From source file:com.enioka.jqm.api.HibernateClient.java
private Integer highlanderMode(JobDef jd, EntityManager em) { // Synchronization is done through locking the JobDef em.lock(jd, LockModeType.PESSIMISTIC_WRITE); // Do the analysis Integer res = null;// ww w . jav a2s. c om jqmlogger.trace("Highlander mode analysis is begining"); ArrayList<JobInstance> jobs = (ArrayList<JobInstance>) em .createQuery("SELECT j FROM JobInstance j WHERE j.jd = :j AND j.state = :s", JobInstance.class) .setParameter("j", jd).setParameter("s", State.SUBMITTED).getResultList(); for (JobInstance j : jobs) { jqmlogger.trace("JI seen by highlander: " + j.getId() + j.getState()); if (j.getState().equals(State.SUBMITTED)) { // HIGHLANDER: only one enqueued job can survive! // current request must be cancelled and enqueue must return the id of the existing submitted JI res = j.getId(); break; } } jqmlogger.trace("Highlander mode will return: " + res); return res; }
From source file:net.groupbuy.service.impl.OrderServiceImpl.java
public Order create(Cart cart, Receiver receiver, PaymentMethod paymentMethod, ShippingMethod shippingMethod, CouponCode couponCode, boolean isInvoice, String invoiceTitle, boolean useBalance, String memo, Admin operator) {/*from www . j a va 2 s.co m*/ Assert.notNull(cart); Assert.notNull(cart.getMember()); Assert.notEmpty(cart.getCartItems()); Assert.notNull(receiver); Assert.notNull(paymentMethod); Assert.notNull(shippingMethod); Order order = build(cart, receiver, paymentMethod, shippingMethod, couponCode, isInvoice, invoiceTitle, useBalance, memo); order.setSn(snDao.generate(Sn.Type.order)); if (paymentMethod.getMethod() == PaymentMethod.Method.online) { order.setLockExpire(DateUtils.addSeconds(new Date(), 20)); order.setOperator(operator); } if (order.getCouponCode() != null) { couponCode.setIsUsed(true); couponCode.setUsedDate(new Date()); couponCodeDao.merge(couponCode); } for (Promotion promotion : cart.getPromotions()) { for (Coupon coupon : promotion.getCoupons()) { order.getCoupons().add(coupon); } } Setting setting = SettingUtils.get(); if (setting.getStockAllocationTime() == StockAllocationTime.order || (setting.getStockAllocationTime() == StockAllocationTime.payment && (order.getPaymentStatus() == PaymentStatus.partialPayment || order.getPaymentStatus() == PaymentStatus.paid))) { order.setIsAllocatedStock(true); } else { order.setIsAllocatedStock(false); } orderDao.persist(order); OrderLog orderLog = new OrderLog(); orderLog.setType(Type.create); orderLog.setOperator(operator != null ? operator.getUsername() : null); orderLog.setOrder(order); orderLogDao.persist(orderLog); Member member = cart.getMember(); if (order.getAmountPaid().compareTo(new BigDecimal(0)) > 0) { memberDao.lock(member, LockModeType.PESSIMISTIC_WRITE); member.setBalance(member.getBalance().subtract(order.getAmountPaid())); memberDao.merge(member); Deposit deposit = new Deposit(); deposit.setType(operator != null ? Deposit.Type.adminPayment : Deposit.Type.memberPayment); deposit.setCredit(new BigDecimal(0)); deposit.setDebit(order.getAmountPaid()); deposit.setBalance(member.getBalance()); deposit.setOperator(operator != null ? operator.getUsername() : null); deposit.setMember(member); deposit.setOrder(order); depositDao.persist(deposit); } if (setting.getStockAllocationTime() == StockAllocationTime.order || (setting.getStockAllocationTime() == StockAllocationTime.payment && (order.getPaymentStatus() == PaymentStatus.partialPayment || order.getPaymentStatus() == PaymentStatus.paid))) { for (OrderItem orderItem : order.getOrderItems()) { if (orderItem != null) { Product product = orderItem.getProduct(); productDao.lock(product, LockModeType.PESSIMISTIC_WRITE); if (product != null && product.getStock() != null) { product.setAllocatedStock(product.getAllocatedStock() + (orderItem.getQuantity() - orderItem.getShippedQuantity())); productDao.merge(product); orderDao.flush(); staticService.build(product); } } } } cartDao.remove(cart); return order; }
From source file:business.services.RequestService.java
/** * /*from ww w . ja va 2 s . c o m*/ */ @Transactional public RequestRepresentation forkRequest(User user, String parentId) { HistoricProcessInstance parentInstance = getProcessInstance(parentId); RequestRepresentation parentRequest = new RequestRepresentation(); requestFormService.transferData(parentInstance, parentRequest, user); if (parentRequest.getStatus() != RequestStatus.LAB_REQUEST && parentRequest.getStatus() != RequestStatus.CLOSED) { throw new InvalidActionInStatus( "Forking of requests not allowed in status " + parentRequest.getStatus() + "."); } log.info("Forking request " + parentRequest.getRequestNumber() + " (requester: " + parentRequest.getRequesterId() + ", " + parentRequest.getRequesterEmail() + ")"); // start new process instance Map<String, Object> values = new HashMap<String, Object>(); values.put("initiator", parentRequest.getRequesterId()); values.put("jump_to_data_delivery", Boolean.TRUE); ProcessInstance newInstance = runtimeService.startProcessInstanceByKey("dntp_request_003", values); String childId = newInstance.getProcessInstanceId(); log.info("New forked process instance started: " + childId); runtimeService.addUserIdentityLink(childId, parentRequest.getRequesterId(), IdentityLinkType.STARTER); HistoricProcessInstance childInstance = getProcessInstance(childId); // copy all request properties to the new instance. Map<String, Object> variables = requestFormService.transferFormData(parentRequest, childInstance, user); runtimeService.setVariables(childId, variables); RequestProperties childProperties = requestPropertiesService.findByProcessInstanceId(childId); RequestProperties parentProperties = requestPropertiesService.findByProcessInstanceId(parentId); synchronized (parentProperties) { em.refresh(parentProperties, LockModeType.PESSIMISTIC_WRITE); // generate new request number String childRequestNumber = String.format("%s-A%d", parentProperties.getRequestNumber(), parentProperties.getChildren().size() + 1); log.info("Create child request with number: " + childRequestNumber); childProperties.setRequestNumber(childRequestNumber); // set link between parent and child request childProperties.setParent(parentProperties); parentProperties.getChildren().add(childProperties); em.persist(parentProperties); em.flush(); } // set submit date to now childProperties.setDateSubmitted(new Date()); // copy attachments for (File file : parentProperties.getRequestAttachments()) { File clone = fileService.clone(file); childProperties.getRequestAttachments().add(clone); } for (File file : parentProperties.getAgreementAttachments()) { File clone = fileService.clone(file); childProperties.getAgreementAttachments().add(clone); } for (File file : parentProperties.getMedicalEthicalCommiteeApprovalAttachments()) { File clone = fileService.clone(file); childProperties.getMedicalEthicalCommiteeApprovalAttachments().add(clone); } requestPropertiesService.save(childProperties); childInstance = getProcessInstance(childId); RequestRepresentation childRequest = new RequestRepresentation(); requestFormService.transferData(childInstance, childRequest, null); return childRequest; }
From source file:com.pinterest.rocksplicator.controller.mysql.MySQLTaskQueue.java
@Override public boolean removeTask(final long id) { beginTransaction();//from w ww. j a v a 2s.c om TaskEntity task = getEntityManager().find(TaskEntity.class, id, LockModeType.PESSIMISTIC_WRITE); try { if (task == null) { LOG.error("Cannot find task {}.", id); throw new MySQLTaskQueueException(); } } catch (MySQLTaskQueueException e) { getEntityManager().getTransaction().rollback(); return false; } getEntityManager().remove(task); getEntityManager().getTransaction().commit(); return true; }
From source file:com.enioka.jqm.api.HibernateClient.java
@Override public void cancelJob(int idJob) { EntityManager em = null;// w w w . java 2 s . co m JobInstance ji = null; try { em = getEm(); em.getTransaction().begin(); ji = em.find(JobInstance.class, idJob, LockModeType.PESSIMISTIC_WRITE); if (ji.getState().equals(State.SUBMITTED)) { ji.setState(State.CANCELLED); } else { throw new NoResultException(); } em.getTransaction().commit(); } catch (NoResultException e) { closeQuietly(em); throw new JqmClientException( "the job is already running, has already finished or never existed to begin with"); } try { em.getTransaction().begin(); History h = new History(); h.setId(ji.getId()); h.setJd(ji.getJd()); h.setApplicationName(ji.getJd().getApplicationName()); h.setSessionId(ji.getSessionID()); h.setQueue(ji.getQueue()); h.setQueueName(ji.getQueue().getName()); h.setEnqueueDate(ji.getCreationDate()); h.setUserName(ji.getUserName()); h.setEmail(ji.getEmail()); h.setParentJobId(ji.getParentId()); h.setApplication(ji.getApplication()); h.setModule(ji.getModule()); h.setKeyword1(ji.getKeyword1()); h.setKeyword2(ji.getKeyword2()); h.setKeyword3(ji.getKeyword3()); h.setProgress(ji.getProgress()); h.setStatus(State.CANCELLED); h.setNode(ji.getNode()); if (ji.getNode() != null) { h.setNodeName(ji.getNode().getName()); } em.persist(h); em.createQuery("DELETE FROM JobInstance WHERE id = :i").setParameter("i", ji.getId()).executeUpdate(); em.getTransaction().commit(); } catch (Exception e) { throw new JqmClientException("could not cancel job instance", e); } finally { closeQuietly(em); } }