首页 \ 问答 \ 同步循环队列(Synchronized Circular Queue)

同步循环队列(Synchronized Circular Queue)

我正在实现一个非常简单的同步Circular Queue ,我的一个朋友说它很容易deadlock ! 但我不相信,

实际上当一个线程想要出队(轮询)队列为空时,它必须等到另一个线程入队(提供)一个元素,反之亦然,如果队列已满,

我不是很擅长找到容易出现死锁的代码,你认为它也容易出现死锁吗?

import java.util.ArrayList;

class CircularQueue<T>{
    ArrayList<T> q;
    int front , rear , size;
    public CircularQueue(int size){
        q = new ArrayList<T>();
        for (int i = 0 ; i < size ; i++)
            q.add(null);
        front =  0;
        rear =0;
        this.size = size;
     }
     public void offer(T t) throws InterruptedException{
        synchronized(this){
            if ( (rear + 1) % size == front)
                this.wait();    
        }
        rear = (rear + 1) % size;
        q.set(rear, t);
        this.notify();
     }
     public T poll() throws InterruptedException{
        synchronized(this){
            if (rear == front)
                this.wait();
        }
        front = (front+1) % size;
        T result = q.get(front);
        this.notify();
        return result;
     }
}

I am implementing a very simple synchronized Circular Queue as it follows , a friend of mine says that it's prone to deadlock ! but I don't believe so ,

actually when a thread wants to dequeue (poll) if the queue is empty it has to wait until another thread enqueue (offer) an element and vice versa if the queue is full ,

I am not very good at finding deadlock-prone codes, do you think that it's prone to deadlock too ?

import java.util.ArrayList;

class CircularQueue<T>{
    ArrayList<T> q;
    int front , rear , size;
    public CircularQueue(int size){
        q = new ArrayList<T>();
        for (int i = 0 ; i < size ; i++)
            q.add(null);
        front =  0;
        rear =0;
        this.size = size;
     }
     public void offer(T t) throws InterruptedException{
        synchronized(this){
            if ( (rear + 1) % size == front)
                this.wait();    
        }
        rear = (rear + 1) % size;
        q.set(rear, t);
        this.notify();
     }
     public T poll() throws InterruptedException{
        synchronized(this){
            if (rear == front)
                this.wait();
        }
        front = (front+1) % size;
        T result = q.get(front);
        this.notify();
        return result;
     }
}

原文:https://stackoverflow.com/questions/17240025
更新时间:2022-08-27 12:08

最满意答案

findAllByCompanyCodeAndFileCodeIn(int CompanyCode, List<String> groups)

你不需要@Query 。 Spring数据可以理解来自方法名称的查询。 使用上面的方法。


findAllByCompanyCodeAndFileCodeIn(int CompanyCode, List<String> groups)

You don't need @Query. Spring data can understand the query from method name. Use the above method.

相关问答

更多
  • 在JPQL中,规范中也是如此。 JPA规范不允许将别名赋予获取联接。 问题在于,通过限制联合抓取的上下文,您可以轻松地将自己拍摄在脚下。 加入两次更安全。 ToMany通常比ToOnes更像一个问题。 例如, Select e from Employee e join fetch e.phones p where p.areaCode = '613' 这将错误地返回所有包含'613'区号中号码的员工,但会在返回列表中排除其他地区的电话号码。 这意味着在613和416区号中有电话的员工将丢失416电话号 ...
  • findAllByCompanyCodeAndFileCodeIn(int CompanyCode, List groups) 你不需要@Query 。 Spring数据可以理解来自方法名称的查询。 使用上面的方法。 findAllByCompanyCodeAndFileCodeIn(int CompanyCode, List groups) You don't need @Query. Spring data can understand the query from ...
  • 它与JPQL完全相同。 在这个特定的文档页面中,第一个表中的右列是关于Java和JDO操作符的(如页面中明确说明的那样),但其他一切都是关于纯JPA和JPQL的。 每个JPA实现和ObjectDB也包括对标准的各种扩展。 但是ObjectDB的扩展在文档中明确指定为扩展。 It is exactly the same JPQL. In this specific documentation page, the right column in the first table is about Java and ...
  • 没有可能的供应商扩展,它将无法正常工作,因为根据规范 4.6.4输入参数 ... 输入参数只能用在查询的WHERE子句或HAVING子句中。 It will not work without possible vendor extensions, because according specification: 4.6.4 Input Parameters ... Input parameters can only be used in the WHERE clause or HAVING clause o ...
  • 我找不到任何可以用JPQL直接比较列表的解决方案或文章。 但是有一种机制可以测试值是否为集合的成员 。 这个过程并不优雅,但经过一些调整,我们可以构建一个类似于此的查询(无法测试代码,但我认为它描述了这个想法并且在逻辑上应该起作用): String query = "SELECT c FROM C c"; String checkValue = ""; for(int i = 0; i
  • 最后我们使用原生查询解决了: String query = "SELECT ROUND(subquery.numberf*100/" + features + ",0) AS \"matches\", m.id_model AS \"id_model\", m.name AS \"name\", m.brand AS \"brand\", m.url_pict AS \"url_picture\"" + " FROM (select count(*) AS numberf ...
  • 您不能将LIKE运算符用于DATE AND DATETIME数据类型。 日期,月份,年份等都有一些功能。大多数Persistence Provider受支持。 FUNC('MONTH', date) FUNC('YEAR', date) 对于eclipselink select object(o) from Orders as o WHERE FUNC('YEAR', o.orderDate) = :def 参数 q.setParameter("def", def); You cannot use L ...
  • 我的猜测是它必须在连接方面做比HAVING更多的工作,因为HAVING应该按照EclipseLink文档工作 。 也许尝试这样的事情,看看它是怎么回事: StringBuffer sql = new StringBuffer(); sql.append( " SELECT CR " ); sql.append( " FROM CommitmentRegisterDetail CRD " ); sql.append( " LEFT JOIN CRD.commitmentRegister CR "); sql ...
  • 使用.join() 。 以下是Criteria API文档中的示例 。 对于导航到相关实体类的查询,查询必须通过调用查询根对象或另一个连接对象上的一个From.join方法来定义与相关实体的连接。 连接方法类似于JPQL中的JOIN关键字。 连接的目标使用EntityType类型的Metamodel类来指定连接实体的持久字段或属性。 join方法返回Join 类型的对象,其中X是源实体,Y是连接的目标。 在以下代码片段中,Pet是源实体,Owner是目标,Pet_是静态生成的元模型类: Crite ...
  • 我在http://www.objectdb.com/java/jpa/query/jpql/comparison上找到了这个,这是非常有趣的,很好的问题。 可以使用相等运算符(=,<>,==,!=)来比较用户定义类(实体类和可嵌入类)的实例。 对于实体,如果e1和e2具有相同的类型和相同的主键值,则e1 = e2。 对于可嵌入对象,如果e1和e2具有完全相同的内容,则e1 = e2。 所以它似乎检查对象的主键值和对象的类型。 因此,似乎p.pType = t,它将检查(假设id是主键)p.pType的id, ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)