List of usage examples for java.util.concurrent Semaphore Semaphore
public Semaphore(int permits, boolean fair)
From source file:mitm.common.tools.SendMail.java
public SendMail(String[] args) throws ParseException, IOException, MessagingException, InterruptedException { CommandLineParser parser = new BasicParser(); Options options = createCommandLineOptions(); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("SendMail", options, true); CommandLine commandLine = parser.parse(options, args); smtpHost = commandLine.getOptionValue("h"); smtpPort = optionAsInteger(commandLine, "p", 25); username = commandLine.getOptionValue("u"); password = commandLine.getOptionValue("password"); sender = commandLine.getOptionValue("s"); from = commandLine.getOptionValue("f"); recipients = commandLine.getOptionValue("r"); inFile = commandLine.getOptionValue("in"); subject = commandLine.getOptionValue("su"); count = optionAsInteger(commandLine, "c", 1); threads = optionAsInteger(commandLine, "t", 1); delay = optionAsLong(commandLine, "d", 0L); serverPort = optionAsInteger(commandLine, "sp", 2525); throttle = optionAsInteger(commandLine, "throttle", null); uniqueFrom = commandLine.hasOption("uf"); throtllingSemaphore = throttle != null ? new Semaphore(throttle, true) : null; if (commandLine.hasOption("pwd")) { System.out.println("Please enter your password: "); password = new jline.ConsoleReader().readLine(new Character('*')); }/*from w w w . j a va 2s. co m*/ if (commandLine.hasOption("l")) { startSMTPServer(); /* allow the SMTP server to settle */ ThreadUtils.sleepQuietly(1000); } Address[] recipientsAddresses = getRecipients(recipients); if (recipientsAddresses != null) { MimeMessage message = commandLine.hasOption("in") ? loadMessage(inFile) : MailUtils.loadMessage(System.in); sendMessage(recipientsAddresses, message); } }
From source file:org.apache.pulsar.client.impl.ClientCnx.java
public ClientCnx(ClientConfigurationData conf, EventLoopGroup eventLoopGroup, int protocolVersion) { super(conf.getKeepAliveIntervalSeconds(), TimeUnit.SECONDS); checkArgument(conf.getMaxLookupRequest() > conf.getConcurrentLookupRequest()); this.pendingLookupRequestSemaphore = new Semaphore(conf.getConcurrentLookupRequest(), true); this.waitingLookupRequests = Queues .newArrayBlockingQueue((conf.getMaxLookupRequest() - conf.getConcurrentLookupRequest())); this.authentication = conf.getAuthentication(); this.eventLoopGroup = eventLoopGroup; this.maxNumberOfRejectedRequestPerConnection = conf.getMaxNumberOfRejectedRequestPerConnection(); this.operationTimeoutMs = conf.getOperationTimeoutMs(); this.state = State.None; this.isTlsHostnameVerificationEnable = conf.isTlsHostnameVerificationEnable(); this.hostnameVerifier = new DefaultHostnameVerifier(); this.protocolVersion = protocolVersion; this.timeoutTask = this.eventLoopGroup.scheduleAtFixedRate(() -> checkRequestTimeout(), operationTimeoutMs, operationTimeoutMs, TimeUnit.MILLISECONDS); }
From source file:org.apache.beehive.controls.runtime.bean.ControlBean.java
/** * Configure this bean to be thread-safe given the threading settings of the impl class and * the outer container.//from w w w. j av a2 s .c o m */ private void ensureThreadingBehaviour() { // // If the implementation class requires a guarantee of single-threaded behavior and the // outer container does not guarantee it, then enable invocation locking on this // bean instance. // if (hasSingleThreadedImpl() && !_cbc.hasSingleThreadedParent()) _invokeLock = new Semaphore(1, true); else _invokeLock = null; }
From source file:com.bt.aloha.collections.memory.InMemoryCollectionImpl.java
protected ConcurrentMap<String, Semaphore> getSemaphores() { if (semaphores == null) { semaphores = new ConcurrentHashMap<String, Semaphore>(); for (String infoId : infos.keySet()) semaphores.put(infoId, new Semaphore(1, true)); }// w ww.j a va2 s. c o m return semaphores; }
From source file:edu.chalmers.dat076.moviefinder.service.MovieFileDatabaseHandlerImpl.java
@Override @Transactional/*from w w w.ja v a2 s . c o m*/ public void removeFile(Path path) { try { movieSemaphore.acquire(); List<Movie> movies = movieRepository.findAllByFilePathStartingWith(path.toString()); for (Movie m : movies) { movieRepository.delete(m); } } catch (InterruptedException ex) { } finally { movieSemaphore.release(); } List<Episode> episodes = episodeRepository.findAllByFilePathStartingWith(path.toString()); for (Episode m : episodes) { Semaphore sLock = serieLock.get(m.getSeries().getTitle()); if (sLock == null) { sLock = new Semaphore(1, true); serieLock.put(m.getSeries().getTitle(), sLock); } try { sLock.acquire(); Series s = m.getSeries(); s.getEpisodes().remove(m); episodeRepository.delete(m); if (s.getEpisodes().isEmpty()) { seriesRepository.delete(s); } else { seriesRepository.save(s); } } catch (InterruptedException ex) { } finally { sLock.release(); } } }
From source file:mitm.common.tools.SendMail.java
private void sendMultiThreaded(final MailTransport mailSender, final MimeMessage message, final Address[] recipients) throws InterruptedException { ExecutorService threadPool = Executors.newCachedThreadPool(); final Semaphore semaphore = new Semaphore(threads, true); final long startTime = System.currentTimeMillis(); for (int i = 1; i <= count; i++) { long threadStart = System.currentTimeMillis(); semaphore.acquireUninterruptibly(); threadPool.execute(new Runnable() { @Override// ww w .j av a2s . com public void run() { try { MimeMessage clone = MailUtils.cloneMessage(message); int sent = sentCount.incrementAndGet(); if (uniqueFrom) { Address[] froms = clone.getFrom(); if (froms != null && froms.length > 0) { clone.setFrom( new InternetAddress(sent + EmailAddressUtils.getEmailAddress(froms[0]))); } } mailSender.sendMessage(clone, recipients); long timePassed = DateTimeUtils .millisecondsToSeconds(System.currentTimeMillis() - startTime); StrBuilder sb = new StrBuilder(); sb.append("Message\t" + sent + "\tsent."); if (timePassed > 0) { float msgPerSec = (float) sent / timePassed; sb.append("\tmessages/second\t" + String.format("%.2f", msgPerSec)); } logger.info(sb.toString()); } catch (MessagingException e) { logger.error("Error sending message.", e); } finally { semaphore.release(); } } }); if (forceQuit.get()) { break; } if (throtllingSemaphore != null) { /* for throttling the sending of emails */ throtllingSemaphore.acquire(); } else { /* no throttling so use delay */ long sleepTime = delay - (System.currentTimeMillis() - threadStart); if (sleepTime > 0) { Thread.sleep(sleepTime); } } } threadPool.shutdown(); threadPool.awaitTermination(30, TimeUnit.SECONDS); waitForReceiveThreads(); logger.info("Total sent: " + sentCount.intValue() + ". Total time: " + DateTimeUtils.millisecondsToSeconds(System.currentTimeMillis() - startTime) + " (sec.)"); }
From source file:voldemort.store.routed.RoutedStore.java
public boolean delete(final ByteArray key, final Version version) throws VoldemortException { StoreUtils.assertValidKey(key);/* w w w. j a v a2s.co m*/ final List<Node> nodes = availableNodes(routingStrategy.routeRequest(key.get())); // quickly fail if there aren't enough live nodes to meet the // requirements final int numNodes = nodes.size(); if (numNodes < this.storeDef.getRequiredWrites()) throw new InsufficientOperationalNodesException("Only " + numNodes + " nodes in preference list, but " + this.storeDef.getRequiredWrites() + " writes required."); // A count of the number of successful operations final AtomicInteger successes = new AtomicInteger(0); final AtomicBoolean deletedSomething = new AtomicBoolean(false); // A list of thrown exceptions, indicating the number of failures final List<Exception> failures = Collections.synchronizedList(new LinkedList<Exception>()); // A semaphore indicating the number of completed operations // Once inititialized all permits are acquired, after that // permits are released when an operation is completed. // semaphore.acquire(n) waits for n operations to complete final Semaphore semaphore = new Semaphore(0, false); // Add the operations to the pool for (final Node node : nodes) { this.executor.execute(new Runnable() { public void run() { long startNs = System.nanoTime(); try { boolean deleted = innerStores.get(node.getId()).delete(key, version); successes.incrementAndGet(); deletedSomething.compareAndSet(false, deleted); recordSuccess(node, startNs); } catch (UnreachableStoreException e) { failures.add(e); recordException(node, startNs, e); } catch (VoldemortApplicationException e) { throw e; } catch (Exception e) { failures.add(e); logger.warn("Error in DELETE on node " + node.getId() + "(" + node.getHost() + ")", e); } finally { // signal that the operation is complete semaphore.release(); } } }); } int attempts = Math.min(storeDef.getPreferredWrites(), numNodes); if (this.storeDef.getPreferredWrites() <= 0) { return true; } else { for (int i = 0; i < numNodes; i++) { try { boolean acquired = semaphore.tryAcquire(timeoutMs, TimeUnit.MILLISECONDS); if (!acquired) logger.warn("Delete operation timed out waiting for operation " + i + " to complete after waiting " + timeoutMs + " ms."); // okay, at least the required number of operations have // completed, were they successful? if (successes.get() >= attempts) return deletedSomething.get(); } catch (InterruptedException e) { throw new InsufficientOperationalNodesException("Delete operation interrupted!", e); } } } // If we get to here, that means we couldn't hit the preferred number // of writes, throw an exception if you can't even hit the required // number if (successes.get() < storeDef.getRequiredWrites()) throw new InsufficientOperationalNodesException( this.storeDef.getRequiredWrites() + " deletes required, but " + successes.get() + " succeeded.", failures); else return deletedSomething.get(); }
From source file:org.wso2.carbon.cloud.gateway.transport.CGTransportSender.java
@Override public void sendMessage(MessageContext msgContext, String targetEPR, OutTransportInfo outTransportInfo) throws AxisFault { try {/*from w ww. jav a2 s.c om*/ String requestUri = (String) msgContext.getProperty(Constants.Configuration.TRANSPORT_IN_URL); if (requestUri == null) { handleException("The request URI is null"); } String endpointPrefix = (String) msgContext.getProperty(NhttpConstants.ENDPOINT_PREFIX); if (endpointPrefix == null) { handleException("The ENDPOINT_PREFIX(EPR) is not found"); } Object headers = msgContext.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS); if (headers == null) { handleException("Transport headers are null"); } String requestMsgIdMsgId = msgContext.getMessageID(); if (requestMsgIdMsgId == null) { requestMsgIdMsgId = UUID.randomUUID().toString(); } Message thriftMsg = new Message(); if (msgContext.isDoingMTOM()) { thriftMsg.setIsDoingMTOM(msgContext.isDoingMTOM()); msgContext.setProperty(org.apache.axis2.Constants.Configuration.ENABLE_MTOM, org.apache.axis2.Constants.VALUE_TRUE); } else if (msgContext.isDoingSwA()) { thriftMsg.setIsDoingSwA(msgContext.isDoingSwA()); msgContext.setProperty(org.apache.axis2.Constants.Configuration.ENABLE_SWA, org.apache.axis2.Constants.VALUE_TRUE); } else if (msgContext.isDoingREST()) { thriftMsg.setIsDoingREST(msgContext.isDoingREST()); } thriftMsg.setHttpMethod((String) msgContext.getProperty(Constants.Configuration.HTTP_METHOD)); thriftMsg.setMessageId(requestMsgIdMsgId); thriftMsg.setEpoch(System.currentTimeMillis()); // a class cast exception (if any) will be logged in case mismatch type is returned, // we will not worry about the type because correct type should be returned thriftMsg.setRequestURI(requestUri); thriftMsg.setSoapAction(msgContext.getSoapAction()); OMOutputFormat format = BaseUtils.getOMOutputFormat(msgContext); ByteArrayOutputStream out = new ByteArrayOutputStream(); formatter.writeTo(msgContext, format, out, false); thriftMsg.setMessage(out.toByteArray()); String contentType = formatter.getContentType(msgContext, format, msgContext.getSoapAction()); thriftMsg.setContentType(contentType); if (((Map) headers).containsKey(HTTP.CONTENT_TYPE)) { ((Map) headers).put(HTTP.CONTENT_TYPE, contentType); } thriftMsg.setTransportHeaders((Map) headers); Semaphore available = null; // The csg polling transport on the other side will directly use the EPR as the key for // message buffer. Although this introduce a tight couple between the CGTransport // and CGPollingTransport this is done this way to achieve maximum performance String token = CGThriftServerHandler.getSecureUUID(endpointPrefix); if (token == null) { handleException("No permission to access the server buffers"); } boolean isOutIn = waitForSynchronousResponse(msgContext); if (isOutIn) { available = new Semaphore(0, true); CGThriftServerHandler.getSemaphoreMap().put(requestMsgIdMsgId, available); } CGThriftServerHandler.addRequestMessage(thriftMsg, token); try { if (isOutIn) { // wait until the response is available, this thread will signal by the // semaphore checking thread or send a timeout error if there is no response // with the configured semaphore timeout or if the semaphore received an // interrupted exception try { available.tryAcquire(semaphoreTimeOut, TimeUnit.SECONDS); } catch (InterruptedException ignore) { } // make sure we don't run out of the main memory CGThriftServerHandler.getSemaphoreMap().remove(requestMsgIdMsgId); Message msg = CGThriftServerHandler.getMiddleBuffer().remove(requestMsgIdMsgId); if (msg != null) { handleSyncResponse(msgContext, msg, contentType); } else { // we don't have a response come yet, so send a fault to client log.warn("The semaphore with id '" + requestMsgIdMsgId + "' was time out while " + "waiting for a response, sending a fault to client.."); sendFault(msgContext, new Exception("Times out occurs while waiting for a response")); } } } catch (Exception e) { handleException("Could not process the response message", e); } } catch (Exception e) { handleException("Could not process the request message", e); } }
From source file:com.kitware.tangoproject.paraviewtangorecorder.PointCloudActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_jpoint_cloud); setTitle(R.string.app_name);/*from w w w . ja va2 s.c om*/ mPoseTextView = (TextView) findViewById(R.id.pose); mQuatTextView = (TextView) findViewById(R.id.quat); mPoseCountTextView = (TextView) findViewById(R.id.posecount); mDeltaTextView = (TextView) findViewById(R.id.deltatime); mTangoEventTextView = (TextView) findViewById(R.id.tangoevent); mPoseStatusTextView = (TextView) findViewById(R.id.status); mPointCountTextView = (TextView) findViewById(R.id.pointCount); mTangoServiceVersionTextView = (TextView) findViewById(R.id.version); mApplicationVersionTextView = (TextView) findViewById(R.id.appversion); mAverageZTextView = (TextView) findViewById(R.id.averageZ); mFrequencyTextView = (TextView) findViewById(R.id.frameDelta); mFirstPersonButton = (Button) findViewById(R.id.first_person_button); mFirstPersonButton.setOnClickListener(this); mThirdPersonButton = (Button) findViewById(R.id.third_person_button); mThirdPersonButton.setOnClickListener(this); mTopDownButton = (Button) findViewById(R.id.top_down_button); mTopDownButton.setOnClickListener(this); mTango = new Tango(this); mConfig = mTango.getConfig(TangoConfig.CONFIG_TYPE_CURRENT); mConfig.putBoolean(TangoConfig.KEY_BOOLEAN_DEPTH, true); int maxDepthPoints = mConfig.getInt("max_point_cloud_elements"); mRenderer = new PCRenderer(maxDepthPoints); mGLView = (GLSurfaceView) findViewById(R.id.gl_surface_view); mGLView.setEGLContextClientVersion(2); mGLView.setRenderer(mRenderer); mGLView.setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY); PackageInfo packageInfo; try { packageInfo = this.getPackageManager().getPackageInfo(this.getPackageName(), 0); mApplicationVersionTextView.setText(packageInfo.versionName); } catch (NameNotFoundException e) { e.printStackTrace(); } // Display the version of Tango Service mServiceVersion = mConfig.getString("tango_service_library_version"); mTangoServiceVersionTextView.setText(mServiceVersion); mIsTangoServiceConnected = false; // My initializations mTakeSnapButton = (Button) findViewById(R.id.take_snap_button); mTakeSnapButton.setOnClickListener(this); mFilesWrittenToSDCardTextView = (TextView) findViewById(R.id.fileWritten); mAutoModeSwitch = (Switch) findViewById(R.id.auto_mode_switch); mAutoModeSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { autoMode_SwitchChanged(isChecked); } }); mRecordSwitch = (Switch) findViewById(R.id.record_switch); mRecordSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { record_SwitchChanged(isChecked); } }); mWaitingProgressBar = (ProgressBar) findViewById(R.id.progressBar); mWaitingProgressBar.setVisibility(View.VISIBLE); mWaitingTextView = (TextView) findViewById(R.id.waitingTextView); mWaitingTextView.setVisibility(View.VISIBLE); mWaitingTextView.setText(R.string.waitInitialize); mWaitingLinearLayout = (LinearLayout) findViewById(R.id.waitingBarLayout); mWaitingLinearLayout.setVisibility(View.VISIBLE); mFilename = ""; mNumberOfFilesWritten = 0; mTimeToTakeSnap = false; mTakeSnapButton.setEnabled(false); mAutoMode = false; mAutoModeSwitch.setChecked(false); mIsRecording = false; mRecordSwitch.setChecked(false); mPosePositionBuffer = new ArrayList<float[]>(); mPoseOrientationBuffer = new ArrayList<float[]>(); mPoseTimestampBuffer = new ArrayList<Float>(); mFilenameBuffer = new ArrayList<String>(); mNumPoseInSequence = 0; mXyzIjCallbackCount = 0; mutex_on_mIsRecording = new Semaphore(1, true); mAppIsStarting = true; // End of My initializations }
From source file:biz.source_code.miniConnectionPoolManager.TestMiniConnectionPoolManager.java
/** * Constructs a MiniConnectionPoolManager object. * @param dataSource the data source for the connections. * @param maxConnections the maximum number of connections. * @param timeout the maximum time in seconds to wait for a free connection. *///from w w w.j a v a 2 s . co m public MiniConnectionPoolManager(ConnectionPoolDataSource dataSource, int maxConnections, int timeout) { this.dataSource = dataSource; this.maxConnections = maxConnections; this.timeout = timeout; try { logWriter = dataSource.getLogWriter(); } catch (SQLException e) { } if (maxConnections < 1) throw new IllegalArgumentException("Invalid maxConnections value."); semaphore = new Semaphore(maxConnections, true); recycledConnections = new Stack<PooledConnection>(); poolConnectionEventListener = new PoolConnectionEventListener(); }