Example usage for java.util.concurrent Semaphore acquire

List of usage examples for java.util.concurrent Semaphore acquire

Introduction

In this page you can find the example usage for java.util.concurrent Semaphore acquire.

Prototype

public void acquire() throws InterruptedException 

Source Link

Document

Acquires a permit from this semaphore, blocking until one is available, or the thread is Thread#interrupt interrupted .

Usage

From source file:com.boundlessgeo.geoserver.api.controllers.ThumbnailController.java

/**
 * Creates a thumbnail for the layer as a Resource, and updates the layer with the new thumbnail
 * @param ws The workspace of the layer/*from   w  ww . j  a  va  2  s  . com*/
 * @param layer The layer or layerGroup to get the thumbnail for
 * @return The thumbnail image as a Resource
 * @throws Exception
 */
protected void createThumbnail(WorkspaceInfo ws, PublishedInfo layer, HttpServletRequest baseRequest)
        throws Exception {
    //Sync against this map/layer
    Semaphore s = semaphores.get(layer);
    s.acquire();
    try {
        //(SUITE-1072) Initialize the thumbnail to a blank image in case the WMS request crashes geoserver
        BufferedImage blankImage = new BufferedImage(THUMBNAIL_SIZE * 2, THUMBNAIL_SIZE * 2,
                BufferedImage.TYPE_4BYTE_ABGR);
        Graphics2D g = blankImage.createGraphics();
        g.setColor(new Color(0, 0, 0, 0));
        g.fillRect(0, 0, blankImage.getWidth(), blankImage.getHeight());
        writeThumbnail(layer, blankImage);

        //Set up getMap request
        String url = baseRequest.getScheme() + "://localhost:" + baseRequest.getLocalPort()
                + baseRequest.getContextPath() + "/" + ws.getName() + "/wms/reflect";

        url += "?FORMAT=" + MIME_TYPE;

        ReferencedEnvelope bbox = null;
        if (layer instanceof LayerInfo) {
            url += "&LAYERS=" + layer.getName();
            url += "&STYLES=" + ((LayerInfo) layer).getDefaultStyle().getName();
            bbox = ((LayerInfo) layer).getResource().boundingBox();
        } else if (layer instanceof LayerGroupInfo) {

            LayerGroupHelper helper = new LayerGroupHelper((LayerGroupInfo) layer);
            bbox = ((LayerGroupInfo) layer).getBounds();
            url += "&CRS=" + CRS.toSRS(bbox.getCoordinateReferenceSystem());

            List<LayerInfo> layerList = helper.allLayersForRendering();
            if (layerList.size() > 0) {
                url += "&LAYERS=";
                for (int i = 0; i < layerList.size(); i++) {
                    if (i > 0) {
                        url += ",";
                    }
                    url += layerList.get(i) == null ? "" : layerList.get(i).getName();
                }
            }
            List<StyleInfo> styleList = helper.allStylesForRendering();
            if (styleList.size() > 0) {
                url += "&STYLES=";
                for (int i = 0; i < styleList.size(); i++) {
                    if (i > 0) {
                        url += ",";
                    }
                    if (styleList.get(i) == null) {
                        url += layerList.get(i).getDefaultStyle() == null ? ""
                                : layerList.get(i).getDefaultStyle().getName();
                    } else {
                        url += styleList.get(i) == null ? "" : styleList.get(i).getName();
                    }
                }
            }
        } else {
            throw new RuntimeException("layer must be one of LayerInfo or LayerGroupInfo");
        }
        //Set the size of the HR thumbnail
        //Take the smallest bbox dimension as the min dimension. We can then crop the other 
        //dimension to give a square thumbnail
        url += "&BBOX=" + ((float) bbox.getMinX()) + "," + ((float) bbox.getMinY()) + ","
                + ((float) bbox.getMaxX()) + "," + ((float) bbox.getMaxY());
        if (bbox.getWidth() < bbox.getHeight()) {
            url += "&WIDTH=" + (2 * THUMBNAIL_SIZE);
            url += "&HEIGHT=" + (2 * THUMBNAIL_SIZE * Math.round(bbox.getHeight() / bbox.getWidth()));
        } else {
            url += "&HEIGHT=" + (2 * THUMBNAIL_SIZE);
            url += "&WIDTH=" + (2 * THUMBNAIL_SIZE * Math.round(bbox.getWidth() / bbox.getHeight()));
        }

        //Run the getMap request through the WMS Reflector
        //WebMap response = wms.reflect(request);            
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("GET");
        BufferedImage image = ImageIO.read(con.getInputStream());
        if (image == null) {
            throw new RuntimeException(
                    "Failed to encode thumbnail for " + ws.getName() + ":" + layer.getName());
        }
        writeThumbnail(layer, image);
    } finally {
        s.release();
    }
}

From source file:de.codecentric.batch.jsr352.CustomJsrJobOperator.java

@Override
public long start(String jobName, Properties params) throws JobStartException, JobSecurityException {
    final JsrXmlApplicationContext batchContext = new JsrXmlApplicationContext(params);
    batchContext.setValidating(false);//from   ww w . j  a  v a  2  s  .co m

    Resource batchXml = new ClassPathResource("/META-INF/batch.xml");
    String jobConfigurationLocation = "/META-INF/batch-jobs/" + jobName + ".xml";
    Resource jobXml = new ClassPathResource(jobConfigurationLocation);

    if (batchXml.exists()) {
        batchContext.load(batchXml);
    }

    if (jobXml.exists()) {
        batchContext.load(jobXml);
    }

    AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder
            .genericBeanDefinition("org.springframework.batch.core.jsr.JsrJobContextFactoryBean")
            .getBeanDefinition();
    beanDefinition.setScope(BeanDefinition.SCOPE_SINGLETON);
    batchContext.registerBeanDefinition(JSR_JOB_CONTEXT_BEAN_NAME, beanDefinition);

    batchContext.setParent(parentContext);

    try {
        batchContext.refresh();
    } catch (BeanCreationException e) {
        throw new JobStartException(e);
    }

    Assert.notNull(jobName, "The job name must not be null.");

    final org.springframework.batch.core.JobExecution jobExecution;

    try {
        JobParameters jobParameters = jobParametersConverter.getJobParameters(params);
        String[] jobNames = batchContext.getBeanNamesForType(Job.class);

        if (jobNames == null || jobNames.length <= 0) {
            throw new BatchRuntimeException("No Job defined in current context");
        }

        org.springframework.batch.core.JobInstance jobInstance = jobRepository.createJobInstance(jobNames[0],
                jobParameters);
        jobExecution = jobRepository.createJobExecution(jobInstance, jobParameters, jobConfigurationLocation);
    } catch (Exception e) {
        throw new JobStartException(e);
    }

    try {
        final Semaphore semaphore = new Semaphore(1);
        final List<Exception> exceptionHolder = Collections.synchronizedList(new ArrayList<Exception>());
        semaphore.acquire();

        taskExecutor.execute(new Runnable() {

            @Override
            public void run() {
                JsrJobContextFactoryBean factoryBean = null;
                try {
                    factoryBean = (JsrJobContextFactoryBean) batchContext
                            .getBean("&" + JSR_JOB_CONTEXT_BEAN_NAME);
                    factoryBean.setJobExecution(jobExecution);
                    final AbstractJob job = batchContext.getBean(AbstractJob.class);
                    addListenerToJobService.addListenerToJob(job);
                    semaphore.release();
                    // Initialization of the JobExecution for job level dependencies
                    jobRegistry.register(job, jobExecution);
                    job.execute(jobExecution);
                    jobRegistry.remove(jobExecution);
                } catch (Exception e) {
                    exceptionHolder.add(e);
                } finally {
                    if (factoryBean != null) {
                        factoryBean.close();
                    }

                    batchContext.close();

                    if (semaphore.availablePermits() == 0) {
                        semaphore.release();
                    }
                }
            }
        });

        semaphore.acquire();
        if (exceptionHolder.size() > 0) {
            semaphore.release();
            throw new JobStartException(exceptionHolder.get(0));
        }
    } catch (Exception e) {
        if (jobRegistry.exists(jobExecution.getId())) {
            jobRegistry.remove(jobExecution);
        }
        jobExecution.upgradeStatus(BatchStatus.FAILED);
        if (jobExecution.getExitStatus().equals(ExitStatus.UNKNOWN)) {
            jobExecution.setExitStatus(ExitStatus.FAILED.addExitDescription(e));
        }
        jobRepository.update(jobExecution);

        if (batchContext.isActive()) {
            batchContext.close();
        }

        throw new JobStartException(e);
    }
    return jobExecution.getId();
}

From source file:edu.chalmers.dat076.moviefinder.service.MovieFileDatabaseHandlerImpl.java

@Override
@Transactional/*www.j a va 2s.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:org.apache.asterix.experiment.client.SpatialQueryGenerator.java

public void start() throws Exception {
    final Semaphore sem = new Semaphore(0);
    threadPool.submit(new QueryGenerator(sem, restHost, restPort, orchHost, orchPort, partitionRangeStart,
            duration, openStreetMapFilePath, isIndexOnlyPlan));
    sem.acquire();
}

From source file:com.bt.aloha.collections.memory.InMemoryCollectionImpl.java

public void replace(T info) {
    if (info == null)
        throw new IllegalArgumentException(String.format(
                "Trying to replace element in collection %s with null info", this.getClass().getSimpleName()));

    String infoId = info.getId();
    log.debug(String.format("InMemoryInfoCollection replacing %s", infoId));
    Semaphore semaphore = getSemaphores().get(infoId);
    if (semaphore == null)
        throw new IllegalArgumentException(
                String.format("Trying to replace non-existing info %s in collection %s", infoId,
                        this.getClass().getSimpleName()));

    try {/* w ww.  j  av a  2 s.  c  o  m*/
        semaphore.acquire();
    } catch (InterruptedException e) {
        log.error(String.format(FAILED_TO_READ_OBJECT_MESSAGE, infoId, this.getClass().getSimpleName(),
                e.getMessage()), e);
        throw new CollectionAccessInterruptedException(String.format(FAILED_TO_READ_OBJECT_MESSAGE, infoId,
                this.getClass().getSimpleName(), e.getMessage()), e);
    }

    try {
        T oldInfo = infos.get(infoId);
        if (!oldInfo.getVersionId().equals(info.getVersionId()))
            throw new ConcurrentUpdateException(infoId, String.format(
                    "Info %s modified in collection %s, try again", infoId, this.getClass().getSimpleName()));

        T newInfo = info.cloneObject();
        newInfo.updateVersionId();
        doExtraUpdates(info, newInfo);
        infos.put(infoId, (T) newInfo);
        info.setVersionId(newInfo.getVersionId());
        log.debug(String.format("Replaced info %s, new version %s", infoId, newInfo.getVersionId()));
    } finally {
        semaphore.release();
    }
}

From source file:com.bt.sdk.callcontrol.sip.util.EhCacheCollectionImpl.java

@SuppressWarnings("unchecked")
public T get(String infoId) {
    if (infoId == null)
        throw new IllegalArgumentException("Info id must not be null");

    Semaphore semaphore = (Semaphore) semaphoreCache.get(infoId).getObjectValue();
    if (semaphore == null) {
        log.debug(String.format("No info object for %s in %s, returning null ", infoId,
                this.getClass().getSimpleName()));
        return null;
    }// w  w  w. j a v a  2  s. com

    try {
        semaphore.acquire();
    } catch (InterruptedException e) {
        log.error(String.format(FAILED_TO_READ_OBJECT_MESSAGE, infoId, this.getClass().getSimpleName(),
                e.getMessage()));
        throw new CollectionAccessInterruptedException(String.format(FAILED_TO_READ_OBJECT_MESSAGE, infoId,
                this.getClass().getSimpleName(), e.getMessage()), e);
    }
    try {
        T result = ((T) cache.get(infoId).getObjectValue()).cloneObject();

        log.debug(String.format("Retrieved info %s with version %s", infoId, result.getVersionId()));
        return (T) result;
    } finally {
        semaphore.release();
    }
}

From source file:com.netflix.curator.framework.recipes.queue.TestBoundedDistributedQueue.java

@Test
public void testSimple() throws Exception {
    Timing timing = new Timing();
    DistributedQueue<String> queue = null;
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(),
            timing.connection(), new RetryOneTime(1));
    try {/*from ww w  .j ava2  s  .  c o  m*/
        client.start();

        final List<String> messages = new CopyOnWriteArrayList<String>();
        final CountDownLatch latch = new CountDownLatch(2);
        final Semaphore semaphore = new Semaphore(0);
        QueueConsumer<String> consumer = new QueueConsumer<String>() {
            @Override
            public void consumeMessage(String message) throws Exception {
                messages.add(message);
                semaphore.acquire();
            }

            @Override
            public void stateChanged(CuratorFramework client, ConnectionState newState) {
            }
        };
        queue = QueueBuilder.builder(client, consumer, serializer, "/queue")
                .executor(Executors.newSingleThreadExecutor()).maxItems(1).buildQueue();
        queue.start();

        QueuePutListener<String> listener = new QueuePutListener<String>() {
            @Override
            public void putCompleted(String item) {
                latch.countDown();
            }

            @Override
            public void putMultiCompleted(MultiItem<String> items) {
            }
        };
        queue.getPutListenerContainer().addListener(listener);

        Assert.assertTrue(queue.put("1", timing.milliseconds(), TimeUnit.MILLISECONDS)); // should end up in consumer
        Assert.assertTrue(queue.put("2", timing.milliseconds(), TimeUnit.MILLISECONDS)); // should sit blocking in DistributedQueue
        Assert.assertTrue(timing.awaitLatch(latch));
        timing.sleepABit();
        Assert.assertFalse(queue.put("3", timing.multiple(.5).milliseconds(), TimeUnit.MILLISECONDS));

        semaphore.release(100);
        Assert.assertTrue(queue.put("3", timing.milliseconds(), TimeUnit.MILLISECONDS));
        Assert.assertTrue(queue.put("4", timing.milliseconds(), TimeUnit.MILLISECONDS));
        Assert.assertTrue(queue.put("5", timing.milliseconds(), TimeUnit.MILLISECONDS));

        for (int i = 0; i < 5; ++i) {
            if (messages.size() == 3) {
                break;
            }
            timing.sleepABit();
        }
        timing.sleepABit();

        Assert.assertEquals(messages, Arrays.asList("1", "2", "3", "4", "5"));
    } finally {
        IOUtils.closeQuietly(queue);
        IOUtils.closeQuietly(client);
    }
}

From source file:org.kuali.mobility.icons.service.IconsServiceImpl.java

/**
 * Creates the required file on the filesystem
 *
 * @param file File to write too//from ww w.j a  v  a  2  s  . c  o m
 * @param icon WebIcon that we need to create a file of
 * @return size The size of the icon (this size must have the multiplier applied already)
 */
private File createFile(final File file, WebIcon icon, int size) {
    Semaphore oneToAdd = new Semaphore(1);
    /*
     * If there currently is a semaphore for the filename, the existing sema will be returned,
     * else the new semaphore will be added and return null (because there is no old value)
     */
    Semaphore sema = lockingMap.putIfAbsent(file.getName(), oneToAdd);
    if (sema == null) {
        sema = oneToAdd;
    }
    try {

        sema.acquire(); // Second concurrent user will wait here
        if (imageFileExists(file)) {
            return file;
        }
        file.createNewFile();

        Resource iconResource = applicationContext.getResource(icon.getPath());
        PNGTranscoder t = new PNGTranscoder();
        t.addTranscodingHint(PNGTranscoder.KEY_MAX_HEIGHT, new Float(size));
        t.addTranscodingHint(PNGTranscoder.KEY_MAX_WIDTH, new Float(size));
        t.addTranscodingHint(PNGTranscoder.KEY_BACKGROUND_COLOR, new Color(0, 0, 0, 0));
        OutputStream ostream = new FileOutputStream(file);

        // Create the transcoder input.
        TranscoderInput input = new TranscoderInput(iconResource.getInputStream());

        // Create the transcoder output.
        TranscoderOutput output = new TranscoderOutput(ostream);

        // Save the image.
        t.transcode(input, output);

        // Flush and close the stream.
        ostream.flush();
        ostream.close();
    } catch (Exception ex) {
        LOG.warn("Exception while creating file", ex);
        if (file.exists()) {
            file.delete();
        }
    } finally {
        sema.release();
    }
    return file;
}

From source file:com.bt.sdk.callcontrol.sip.util.EhCacheCollectionImpl.java

@SuppressWarnings("unchecked")
public void replace(T info) {
    if (info == null)
        throw new IllegalArgumentException(String.format(
                "Trying to replace element in collection %s with null info", this.getClass().getSimpleName()));

    String infoId = info.getId();
    log.debug(String.format("InMemoryInfoCollection replacing %s", infoId));
    if (!semaphoreCache.getKeys().contains(infoId))
        throw new IllegalArgumentException(
                String.format("Trying to replace non-existing info %s in collection %s", infoId,
                        this.getClass().getSimpleName()));
    Semaphore semaphore = (Semaphore) semaphoreCache.get(infoId).getObjectValue();
    if (semaphore == null)
        throw new IllegalArgumentException(
                String.format("Trying to replace non-existing info %s in collection %s", infoId,
                        this.getClass().getSimpleName()));

    try {/*from ww  w .j a va  2 s .  c o  m*/
        semaphore.acquire();
    } catch (InterruptedException e) {
        log.error(String.format(FAILED_TO_READ_OBJECT_MESSAGE, infoId, this.getClass().getSimpleName(),
                e.getMessage()), e);
        throw new CollectionAccessInterruptedException(String.format(FAILED_TO_READ_OBJECT_MESSAGE, infoId,
                this.getClass().getSimpleName(), e.getMessage()), e);
    }

    try {
        //T oldInfo = infos.get(infoId);
        T oldInfo = (T) cache.get(infoId).getObjectValue();
        if (!oldInfo.getVersionId().equals(info.getVersionId()))
            throw new ConcurrentUpdateException(infoId, String.format(
                    "Info %s modified in collection %s, try again", infoId, this.getClass().getSimpleName()));

        T newInfo = info.cloneObject();
        newInfo.updateVersionId();
        doExtraUpdates(info, newInfo);
        //infos.put(infoId, (T)newInfo);
        cache.put(new Element(infoId, newInfo));
        info.setVersionId(newInfo.getVersionId());
        log.debug(String.format("Replaced info %s, new version %s", infoId, newInfo.getVersionId()));
    } finally {
        semaphore.release();
    }
}

From source file:org.openengsb.opencit.core.projectmanager.internal.ProjectManagerImplTest.java

@Test
@SuppressWarnings("unchecked")
public void buildManually_shouldSuspendPoller() throws Exception {
    final Semaphore eventSync = new Semaphore(0);
    when(workflowService.startFlow(eq("ci"), any(Map.class))).thenReturn(1L);
    doAnswer(new Answer<Void>() {
        @Override//  ww w  . j  av a2 s  .co m
        public Void answer(InvocationOnMock invocation) throws Throwable {
            eventSync.acquire();
            return null;
        }
    }).when(workflowService).waitForFlowToFinish(eq(1L), anyLong());
    when(scmMock.update()).thenReturn(null);

    Project project = new Project("test");
    project.setState(State.OK);
    projectManager.createProject(project);
    Thread.sleep(200);
    scheduler.scheduleProjectForBuild("test", new TestBuild());
    assertThat(scheduler.isProjectBuilding("test"), is(true));
    assertThat(scheduler.isProjectPolling("test"), is(false));
    Thread.sleep(200);
    verify(scmMock).update();

    eventSync.release();
    Thread.sleep(200);

    assertThat(scheduler.isProjectBuilding("test"), is(false));
    assertThat(scheduler.isProjectPolling("test"), is(true));
}