Java Code Examples for java.util.Deque#offer()

The following examples show how to use java.util.Deque#offer() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AbstractPageDataProvider.java    From xframium-java with GNU General Public License v3.0 6 votes vote down vote up
@Override
public PageData getRecord( String recordType )
{
	try
	{
		Deque<PageData> dataList = recordMap.get( getRecordType( recordType ) ).getRecordList();
		
		if ( dataList instanceof LinkedBlockingDeque )
			return ( (LinkedBlockingDeque<PageData>) dataList ).pollFirst( waitTimeOut, TimeUnit.SECONDS );
		else
		{
			PageData pageData = dataList.pollFirst();
			dataList.offer( pageData );
			return pageData;
		}
	}
	catch( Exception e )
	{
		log.error( "Error acquiring page data [" + getRecordType( recordType ) + "] - " + e.getMessage() );
		return null;
	}
}
 
Example 2
Source File: PrintFromTopToBottom.java    From AtOffer with Apache License 2.0 6 votes vote down vote up
public ArrayList<Integer> printFromTopToBottom(TreeNode root) {
    ArrayList<Integer> res = new ArrayList<>();
    if(root == null) {
        return res;
    }

    Deque<TreeNode> nodes = new LinkedList<>();
    nodes.offer(root);
    while(!nodes.isEmpty()) {
        TreeNode node = nodes.poll();
        res.add(node.val);
        if(node.left != null) {
            nodes.offer(node.left);
        }
        if(node.right != null) {
            nodes.offer(node.right);
        }
    }

    return res;
}
 
Example 3
Source File: BFSByIterative.java    From hellokoding-courses with MIT License 6 votes vote down vote up
public static void bfsByIterative(GraphUndirectedByAdjacencyList g, int v) {
    boolean[] visited = new boolean[g.getV()];
    Deque<Integer> queue = new ArrayDeque<>();
    queue.offer(v);

    while (!queue.isEmpty()) {
        v = queue.poll();

        if (!visited[v]) {
            visited[v] = true;
            System.out.printf("%d ", v);

            for (Integer w : g.getAdjacencyList().get(v)) {
                queue.offer(w);
            }
        }
    }
}
 
Example 4
Source File: BFSByIterativeWithColor.java    From hellokoding-courses with MIT License 6 votes vote down vote up
public static void bfsByIterativeWithColor(GraphUndirectedByAdjacencyList g, int v) {
    int[] color = new int[g.getV()];
    Deque<Integer> queue = new ArrayDeque<>();
    queue.offer(v);

    while (!queue.isEmpty()) {
        v = queue.poll();

        if (color[v] == WHITE) {
            color[v] = GRAY;
            System.out.printf("%d ", v);

            for (Integer w : g.getAdjacencyList().get(v)) {
                queue.offer(w);
            }

            color[v] = BLACK;
        }
    }
}
 
Example 5
Source File: AmbientBrightnessStatsTracker.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
private AmbientBrightnessDayStats getOrCreateDayStats(
        Deque<AmbientBrightnessDayStats> userStats, LocalDate localDate) {
    AmbientBrightnessDayStats lastBrightnessStats = userStats.peekLast();
    if (lastBrightnessStats != null && lastBrightnessStats.getLocalDate().equals(
            localDate)) {
        return lastBrightnessStats;
    } else {
        AmbientBrightnessDayStats dayStats = new AmbientBrightnessDayStats(localDate,
                BUCKET_BOUNDARIES_FOR_NEW_STATS);
        if (userStats.size() == MAX_DAYS_TO_TRACK) {
            userStats.poll();
        }
        userStats.offer(dayStats);
        return dayStats;
    }
}
 
Example 6
Source File: DocumentStoreTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static void flushIfNeeded(
        final boolean flush,
        @NonNull final ClusteredIndexables.DocumentStore store,
        @NonNull final Deque<? super String> collector) {
    if (flush) {
        for (IndexDocument doc : store) {
            collector.offer(doc.getPrimaryKey());
        }
        store.clear();
    }
}
 
Example 7
Source File: FolderArchive.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@NonNull
private static List<JavaFileObject> visit(
        @NonNull final File folder,
        @NonNull final File root,
        @NonNull final Charset encoding,
        @NullAllowed final JavaFileFilterImplementation filter,
        final boolean recursive,
        @NonNull Function<File,JavaFileObject.Kind> accept) {
    final List<JavaFileObject> res = new ArrayList<>();
    final Deque<File> todo = new ArrayDeque<>();
    todo.offer(folder);
    while (!todo.isEmpty()) {
        final File active = todo.removeLast();  //DFS
        final File[] content = active.listFiles();
        if (content != null) {
            for (File f : content) {
                final JavaFileObject.Kind fKind = accept.apply(f);
                if (fKind != null) {
                    res.add(FileObjects.fileFileObject(
                        f,
                        root,
                        filter,
                        fKind == JavaFileObject.Kind.CLASS ?
                                UNKNOWN_CHARSET :
                                encoding));
                } else if (recursive && f.isDirectory()) {
                    todo.offer(f);
                }
            }
        }
    }
    return Collections.unmodifiableList(res);
}
 
Example 8
Source File: SourcePrefetcherTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testDeadlock208663() throws Exception {
    CompileTuple ct = files.iterator().next();
    final FileObject fo = URLMapper.findFileObject(ct.indexable.getURL());
    final FileLock lck = fo.lock();
    try {
        final OutputStream out = new BufferedOutputStream(fo.getOutputStream(lck));
        try {
            for (int i = 0; i<101; i++) {
                out.write('a');
            }
        } finally {
            out.close();
        }
    } finally {
        lck.releaseLock();
    }
    
    JavaIndexerWorker.TEST_DO_PREFETCH = true;
    JavaIndexerWorker.BUFFER_SIZE = 100;
    final LogHandler handler = new LogHandler();
    handler.expect("Using concurrent iterator, {0} workers");    //NOI18N
    final Logger log = Logger.getLogger(JavaIndexerWorker.class.getName());
    log.setLevel(Level.FINE);
    log.addHandler(handler);
    try {
        SourcePrefetcher pf = SourcePrefetcher.create(files, SuspendSupport.NOP);
        assertTrue(handler.isFound());
        final Deque<CompileTuple> got = new ArrayDeque<CompileTuple>(FILE_COUNT);
        while (pf.hasNext()) {
            ct = pf.next();
            assertNotNull(getCache(ct.jfo));
            got.offer(ct);
            pf.remove();
            assertNull(getCache(ct.jfo));
        }
        assertCollectionsEqual(files,got);
    } finally {
        log.removeHandler(handler);
    }
}
 
Example 9
Source File: AbstractPageDataProvider.java    From xframium-java with GNU General Public License v3.0 5 votes vote down vote up
public void putRecord( PageData pageData )
{
	if ( pageData != null )
	{
		Deque<PageData> dataList = recordMap.get( pageData.getType() ).getRecordList();
		if ( dataList instanceof LinkedBlockingDeque )
			dataList.offer( pageData );
	}
}
 
Example 10
Source File: PullBuffer.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
public boolean addDelayRequest(DelayRequest delayRequest) {
    Deque<DelayRequest> waitQueue = waitQueueMap.computeIfAbsent(
            getRequestTopic(delayRequest.getRequest()), topic -> new LinkedBlockingDeque<>(MAX_WAIT_REQUEST_QUEUE_SIZE));

    if (!waitQueue.offer(delayRequest)) {
        doCleanWaitQueue(waitQueue);
        return waitQueue.offer(delayRequest);
    } else {
        return true;
    }
}
 
Example 11
Source File: ConverterPagerAdapter.java    From power-adapters with Apache License 2.0 5 votes vote down vote up
void put(@NonNull Object itemViewType, @NonNull View v) {
    Deque<View> views = mViews.get(itemViewType);
    if (views == null) {
        views = new ArrayDeque<>();
        mViews.put(itemViewType, views);
    }
    views.offer(v);
}
 
Example 12
Source File: TreeTraversalInSpiralOrder.java    From interview with Apache License 2.0 5 votes vote down vote up
/**
 * One deque with delimiter to print tree in spiral order
 */
public void spiralWithOneDequeDelimiter(Node root)
{
    if(root == null){
        return;
    }
    Deque<Node> q = new LinkedList<>();
    q.offer(null);
    q.offerFirst(root);
    //if only delimiter(in this case null) is left in queue then break
    while(q.size() > 1){
        root = q.peekFirst();
        while(root != null){
            root = q.pollFirst();
            System.out.print(root.data + " ");
            if(root.left != null){
                q.offerLast(root.left);
            }
            if(root.right != null){
                q.offerLast(root.right);
            }
            root = q.peekFirst();
        }
        root = q.peekLast();
        while(root != null){
            System.out.print(root.data + " ");
            root = q.pollLast();
            if(root.right != null){
                q.offerFirst(root.right);
            }
            if(root.left != null){
                q.offerFirst(root.left);
            }
            root = q.peekLast();
        }
    }
}
 
Example 13
Source File: JsonOptionsQuery.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@NonNull
public static Result getOptions(@NonNull final FileObject file) {
    Parameters.notNull("file", file);
    final Deque<JsonOptionsQueryImplementation.Result> results = new ArrayDeque<>();
    for (JsonOptionsQueryImplementation impl : Lookup.getDefault().lookupAll(JsonOptionsQueryImplementation.class)) {
        final JsonOptionsQueryImplementation.Result res = impl.getOptions(file);
        if (res != null) {
            results.offer(res);
        }
    }
    return new Result(results);
}
 
Example 14
Source File: AbstractPageDataProvider.java    From xframium-java with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Adds the record.
 *
 * @param pageData the page data
 */
public void addRecord( PageData pageData, String recordType )
{
    allRecordMap.get( recordType ).addRecord( pageData );
    
    if ( !pageData.isActive() )
        return;
    
	Deque<PageData> dataList = recordMap.get( recordType ).getRecordList();
	idMap.put( recordType + "." + pageData.getName(), pageData );
	dataList.offer( pageData );
}
 
Example 15
Source File: SourcePrefetcherTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
protected void setUp() throws Exception {
    super.setUp();
    clearWorkDir();
    final FileObject wdFo = FileUtil.toFileObject(getWorkDir());
    final FileObject srcFolder = FileUtil.createFolder(wdFo, "src");        //NOI18N
    final Deque<CompileTuple> q = new ArrayDeque<CompileTuple>();
    for (int i=0; i<FILE_COUNT; i++) {
        final FileObject file = FileUtil.createData(srcFolder, String.format("file%d.txt",i)); //NOI18N
        final Indexable indexable = SPIAccessor.getInstance().create(new FileObjectIndexable(srcFolder, file));
        final PrefetchableJavaFileObject jfo = FileObjects.fileFileObject(FileUtil.toFile(file), FileUtil.toFile(srcFolder), null, null);
        q.offer(new CompileTuple(jfo,indexable));
    }
    files = q;
}
 
Example 16
Source File: SourcePrefetcherTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testDeletedFile() throws Exception {
    CompileTuple ct = files.iterator().next();
    final FileObject fo = URLMapper.findFileObject(ct.indexable.getURL());        
    fo.delete();
    
    JavaIndexerWorker.TEST_DO_PREFETCH = true;
    final LogHandler handler = new LogHandler();
    handler.expect("Using concurrent iterator, {0} workers");    //NOI18N
    final Logger log = Logger.getLogger(JavaIndexerWorker.class.getName());
    log.setLevel(Level.FINE);
    log.addHandler(handler);
    try {
        SourcePrefetcher pf = SourcePrefetcher.create(files, SuspendSupport.NOP);
        assertTrue(handler.isFound());
        final Deque<CompileTuple> got = new ArrayDeque<CompileTuple>(FILE_COUNT);
        while (pf.hasNext()) {
            ct = pf.next();
            try {
                if (ct != null) {
                    assertNotNull(getCache(ct.jfo));
                    got.offer(ct);
                }
            } finally {
                pf.remove();
            }
            if (ct != null) {
                assertNull(getCache(ct.jfo));
            }
        }
        final List<CompileTuple> allButFirst = new LinkedList<CompileTuple>(files);
        allButFirst.remove(0);
        assertCollectionsEqual(allButFirst,got);
    } finally {
        log.removeHandler(handler);
    }
}
 
Example 17
Source File: Solution.java    From daily-coding-problems with Apache License 2.0 5 votes vote down vote up
private void interleaveStackHelper(Deque<Integer> stack, Deque<Integer> queue, int index) {
    int stackSize = stack.size();
    for (int i = 0; i < stackSize - index; i++) {
        queue.offer(stack.pop());
    }

    while (!queue.isEmpty()) {
        stack.push(queue.remove());
    }

    if (stack.size() - index > 1) {
        interleaveStackHelper(stack, queue, index + 1);
    }
}
 
Example 18
Source File: ArrayDequeUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenOffer_addsAtLast() {
    final Deque<String> deque = new ArrayDeque<>();

    deque.offer("first");
    deque.offer("second");

    assertEquals("second", deque.getLast());
}
 
Example 19
Source File: ClassLoaderSupport.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@NonNull
private static URL[] getRootURLs(@NonNull final ClassPath cp) {
    final List<ClassPath.Entry> entries = cp.entries();
    final Deque<URL> res = new ArrayDeque<>(entries.size());
    for (ClassPath.Entry e : entries) {
        res.offer(e.getURL());
    }
    return res.toArray(new URL[res.size()]);
}
 
Example 20
Source File: VisibilitySupport.java    From netbeans with Apache License 2.0 4 votes vote down vote up
boolean isVisible(
    @NonNull FileObject file,
    @NullAllowed final FileObject root) {
    long st = 0L;
    if (LOGGER.isLoggable(Level.FINER)) {
        st = System.currentTimeMillis();
    }
    try {
        final VisibilityQuery vq = VisibilityQuery.getDefault();
        final Deque<FileObject> fta = new ArrayDeque<FileObject>();
        Boolean vote = null;
        boolean folder = false;
        while (root != null && !root.equals(file)) {
            vote = visibilityCache.get(file);
            if (vote != null) {
                break;
            }
            if (folder || file.isFolder()) {
                fta.offer(file);
            }
            if (!vq.isVisible(file)) {
                vote = Boolean.FALSE;
                break;
            }
            file = file.getParent();
            folder = true;
        }
        if (vote == null) {
            vote = vq.isVisible(file);
            fta.offer(file);
        }
        if (!fta.isEmpty()) {
            synchronized(visibilityCache) {
                for (FileObject nf : fta) {
                    visibilityCache.put(nf, vote);
                }
            }
        }
        return vote;
    } finally {
        if (LOGGER.isLoggable(Level.FINER)) {
            LOGGER.log(
                Level.FINER,
                "reportVisibilityOverhead: {0}",    //NOI18N
                (System.currentTimeMillis() - st));
        }
    }
}