multithreading - Java - threadsafe collection that sorts on remove/take -


i have situation whereby need threadsafe queue runs sort every time remove() method called , when method called. because objects can dynamically change "priority" after have been added collection due external factors. needs threadsafe. there no point extending priorityblockingqueue because run comparison function when additions made. failed find such collection/queue, tried implement own wrapping around array list:

public class blockingsortontakequeue<e> implements queue<e> {     private arraylist<e> m_list;      public blockingsortontakearraylist()     {         m_list = new arraylist<>();     }       @override     public synchronized e remove()      {         m_list.sort(m_comparator);         return m_list.remove(0);     }      .... 

unfortunately, having difficulty figuring out how ensure object type <e> has implement compareable interface, , use objects compareto function when trying sort list (in code have m_comparator unfinished/placeholder).

does know threadsafe queue sorts on remove() or how fix start of custom collection use generic objects compareto function sort list.

it looks you're doing way has done. force comparable interface, write

public class blockingsortontakequeue<e extends comparable<e>> implements queue<e> {   ...   @override   public synchronized e remove() {     collections.sort(m_list);     return m_list.remove(0);   } } 

...though might advantage sort in reverse order, collections.sort(m_list, collections.reverseorder()), , remove last element, since that's faster in arraylist.

it might better identify minimum element, rather sorting entire list, o(n) instead of o(n log n).


Comments

Popular posts from this blog

java - WrongTypeOfReturnValue exception thrown when unit testing using mockito -

php - Magento - Deleted Base url key -

android - How to disable Button if EditText is empty ? -