首页 \ 问答 \ ObjectPool的Stack或LinkedList?(Stack or LinkedList for ObjectPool?)

ObjectPool的Stack或LinkedList?(Stack or LinkedList for ObjectPool?)

我确定对此的正确答案取决于池化对象的类型和工作量,因此我将详细介绍我的实现:

我有一个ObjectPool用于汇集长时间运行的命令行进程。 这些进程通过stdin / stdout进行通信,并执行文件/网络操作。 许多任务比其他任务完成得更快,并且可以快速将进程返回池中。 对池的所有访问必须是线程安全的。

我的问题是,我最好用LIFO / Stack或FIFO / ConcurrentLinkedQueue管理池吗? 我对双方的理由:

  • 堆栈保持“热”对象在游戏中,其中资源可以保持缓存/等。 更长时间。
  • FIFO平衡了进程之间的调用,每个进程都做得更少。 谢谢!

I'm sure the correct answer to this depends on the type of pooled objects and the workload, so I'll detail my implementation a bit:

I have an ObjectPool used to pool long-running command-line processes. These processes communicate via stdin/stdout, and perform file/network operations. Many tasks complete much faster than others and may return processes to the pool quickly. All access to the pool must be thread-safe.

My question is, am I better off managing the pool with a LIFO/Stack, or a FIFO/ConcurrentLinkedQueue? My reasoning on both sides:

  • A stack keeps "hot" objects in play, where resources may remain cached/etc. for longer.
  • A FIFO balances calls more evenly between the processes, with each doing less work. Thanks!

原文:https://stackoverflow.com/questions/10522956
更新时间:2024-03-11 06:03

最满意答案

最后我最终创建了自己的自定义适配器,这样我至少可以更容易地理解发生了什么。

我必须创建几个多选列表,其中一些填充数据库中的数据,另一些填充来自共享首选项。

对于这个显示来自数据库的数据,我创建了以下适配器(我注释了关于图标的行,因为我还没有设置它们):

public class CategoriesLVAdapter extends BaseAdapter {
private Context mContext;
private LayoutInflater mInflater;
private List<Category> categoriesList;

// Constructor
public CategoriesLVAdapter(Context c, List<Category> categories_list){
    mContext = c;
    mInflater = LayoutInflater.from(c);
    categoriesList = categories_list;
}

public List<Category> getCategoriesList(){
    return categoriesList;
}

@Override
public int getCount() {
    return categoriesList.size();
}

@Override
public Object getItem(int position) {
    return categoriesList.get(position);
}

@Override
public long getItemId(int position) {
    return categoriesList.get(position).getID();
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    ViewHolder holder = null;
    if (convertView == null) {
        convertView = mInflater.inflate(R.layout.categories_list_row, null);
        //convertView.setLayoutParams(new ListView.LayoutParams(200, 90));
        holder = new ViewHolder();
        holder.title = (TextView) convertView.findViewById(R.id.categories_list_row_tv);
        //holder.icon = (ImageView) convertView.findViewById(R.id.categories_list_row_iv);

        convertView.setTag(holder);
    } else {
        holder = (ViewHolder) convertView.getTag();         
    }

    //holder.icon.setImageResource(categoriesList.get(position).getDrawableID());
    //holder.icon.setAdjustViewBounds(true);  
    //holder.icon.setScaleType(ImageView.ScaleType.CENTER_CROP);        
    holder.title.setText(categoriesList.get(position).getName());

    return convertView;
}

static class ViewHolder {
    TextView title;
    //ImageView icon;
}

}

在我的活动中,我在调用AlertDialog来填充ListView时使用此适配器,然后使用共享首选项中保存的最后一个预先选择类别:

private void categoriesFilter(){
    AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
    alt_bld.setTitle(resources.getText(R.string.select_categories).toString());

    LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);   
    View layout = inflater.inflate(R.layout.categories_list,(ViewGroup) findViewById(R.id.categories_layout_root));
    categoriesLV = (ListView) layout.findViewById(R.id.categories_list);

    alt_bld.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            String selectedCategoriesString = getSelectedValues(categoriesLV);

            //Update the shared preferences
            prefs.edit().putString(RateDayApplication.PREF_KEY_CATEGORIES, selectedCategoriesString).commit();

            updateFilterDisplay(resources.getText(R.string.cat_title).toString(), selectedCategoriesString, searchedCategoriesTV, "Category");
        }
    });

    alt_bld.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            dialog.cancel();
        }
    });

    String selectedCategoriesString = prefs.getString(RateDayApplication.PREF_KEY_CATEGORIES, new String());
    categoriesLV.setAdapter(new CategoriesLVAdapter(this, categoriesList));

    String[] selectedCategoriesArray = selectedCategoriesString.split(",");

    int categoriesLVLength = categoriesLV.getCount();
    for(int i = 0; i < categoriesLVLength; i++){
        int categoryID = ((Category) categoriesLV.getItemAtPosition(i)).getID();
        if(Arrays.asList(selectedCategoriesArray).contains(String.valueOf(categoryID))){
            categoriesLV.setItemChecked(i, true);
        }
    }

    alt_bld.setView(layout);

    AlertDialog alert = alt_bld.create();   
    alert.show();
}

最后,这是我从数据库处理程序调用的函数,以获取catagories列表:

// Getting All Categories By ID desc
    public List<Category> getCategoriesList() {
        String selectQuery = "SELECT " + CATEGORY_ID + ", " + CATEGORY_NAME + " FROM " + CATEGORY_TABLE + " ORDER BY " + CATEGORY_ID + " ASC";
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null); 

        List<Category> categoriesList = new ArrayList<Category>();//String[] categoriesList = {};

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                Category category = new Category(cursor.getInt(0), cursor.getString(1), false);
                categoriesList.add(category);
            } while (cursor.moveToNext());
        }

        cursor.close();
        db.close();
        return categoriesList;
    }

我认为我之前遇到的问题是因为函数“setItemChecked”有点误导,因为它并不一定意味着必须检查任何东西。 当您使用“setItemChecked”函数时,列表视图中的项目将被选中,有或没有复选框(我的行只包含文本视图)。

在我的列表中选择的行显示为不同的颜色,这在我看来足够简单的多选列表。

我使用的布局非常简单,“categories_list”包含LinearLayout中的ListView,“categories_list_row”包含LinearLayout中的TextView。

希望它可以指导某人!


Finally I ended up creating my own custom adapter, this way I could at least understand more easily what was happening.

I had to create actually several multiselect lists, some populated with data from the database, others from the shared preferences.

For this one displaying data from the DB, I created the following adapter (I commented out the lines about the icons because I did not set them up yet):

public class CategoriesLVAdapter extends BaseAdapter {
private Context mContext;
private LayoutInflater mInflater;
private List<Category> categoriesList;

// Constructor
public CategoriesLVAdapter(Context c, List<Category> categories_list){
    mContext = c;
    mInflater = LayoutInflater.from(c);
    categoriesList = categories_list;
}

public List<Category> getCategoriesList(){
    return categoriesList;
}

@Override
public int getCount() {
    return categoriesList.size();
}

@Override
public Object getItem(int position) {
    return categoriesList.get(position);
}

@Override
public long getItemId(int position) {
    return categoriesList.get(position).getID();
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    ViewHolder holder = null;
    if (convertView == null) {
        convertView = mInflater.inflate(R.layout.categories_list_row, null);
        //convertView.setLayoutParams(new ListView.LayoutParams(200, 90));
        holder = new ViewHolder();
        holder.title = (TextView) convertView.findViewById(R.id.categories_list_row_tv);
        //holder.icon = (ImageView) convertView.findViewById(R.id.categories_list_row_iv);

        convertView.setTag(holder);
    } else {
        holder = (ViewHolder) convertView.getTag();         
    }

    //holder.icon.setImageResource(categoriesList.get(position).getDrawableID());
    //holder.icon.setAdjustViewBounds(true);  
    //holder.icon.setScaleType(ImageView.ScaleType.CENTER_CROP);        
    holder.title.setText(categoriesList.get(position).getName());

    return convertView;
}

static class ViewHolder {
    TextView title;
    //ImageView icon;
}

}

In my activity, I use this adapter when the AlertDialog is called to populate the ListView, then I pre-select the categories using the last ones saved in the shared preferences:

private void categoriesFilter(){
    AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
    alt_bld.setTitle(resources.getText(R.string.select_categories).toString());

    LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);   
    View layout = inflater.inflate(R.layout.categories_list,(ViewGroup) findViewById(R.id.categories_layout_root));
    categoriesLV = (ListView) layout.findViewById(R.id.categories_list);

    alt_bld.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            String selectedCategoriesString = getSelectedValues(categoriesLV);

            //Update the shared preferences
            prefs.edit().putString(RateDayApplication.PREF_KEY_CATEGORIES, selectedCategoriesString).commit();

            updateFilterDisplay(resources.getText(R.string.cat_title).toString(), selectedCategoriesString, searchedCategoriesTV, "Category");
        }
    });

    alt_bld.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            dialog.cancel();
        }
    });

    String selectedCategoriesString = prefs.getString(RateDayApplication.PREF_KEY_CATEGORIES, new String());
    categoriesLV.setAdapter(new CategoriesLVAdapter(this, categoriesList));

    String[] selectedCategoriesArray = selectedCategoriesString.split(",");

    int categoriesLVLength = categoriesLV.getCount();
    for(int i = 0; i < categoriesLVLength; i++){
        int categoryID = ((Category) categoriesLV.getItemAtPosition(i)).getID();
        if(Arrays.asList(selectedCategoriesArray).contains(String.valueOf(categoryID))){
            categoriesLV.setItemChecked(i, true);
        }
    }

    alt_bld.setView(layout);

    AlertDialog alert = alt_bld.create();   
    alert.show();
}

Finally here is the function I call from my database handler to get the list of catagories:

// Getting All Categories By ID desc
    public List<Category> getCategoriesList() {
        String selectQuery = "SELECT " + CATEGORY_ID + ", " + CATEGORY_NAME + " FROM " + CATEGORY_TABLE + " ORDER BY " + CATEGORY_ID + " ASC";
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null); 

        List<Category> categoriesList = new ArrayList<Category>();//String[] categoriesList = {};

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                Category category = new Category(cursor.getInt(0), cursor.getString(1), false);
                categoriesList.add(category);
            } while (cursor.moveToNext());
        }

        cursor.close();
        db.close();
        return categoriesList;
    }

I think my problem before was coming from the fact that the function "setItemChecked" is a little misleading because it does not mean necessarily that anything is checked. When you use the function "setItemChecked", the item in the list view becomes selected, with or without a checkbox (my rows only contain text views).

The rows selected in my list appear in a different color, and that's enough in my opinion for a simple multi selection list.

The layouts I used are quite simple, "categories_list" contains a ListView in a LinearLayout and "categories_list_row" contains a TextView in a LinearLayout.

Hope it may guide someone!

相关问答

更多

相关文章

更多

最新问答

更多
  • 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
  • 如何通过引用返回对象?(How is returning an object by reference possible?)
  • 矩阵如何存储在内存中?(How are matrices stored in memory?)
  • 每个请求的Java新会话?(Java New Session For Each Request?)
  • css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)
  • 无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)
  • xcode语法颜色编码解释?(xcode syntax color coding explained?)
  • 在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)
  • 从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)
  • 从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))
  • 西安哪有PLC可控制编程的培训
  • 在Entity Framework中选择基类(Select base class in Entity Framework)
  • 在Android中出现错误“数据集和渲染器应该不为null,并且应该具有相同数量的系列”(Error “Dataset and renderer should be not null and should have the same number of series” in Android)
  • 电脑二级VF有什么用
  • Datamapper Ruby如何添加Hook方法(Datamapper Ruby How to add Hook Method)
  • 金华英语角.
  • 手机软件如何制作
  • 用于Android webview中图像保存的上下文菜单(Context Menu for Image Saving in an Android webview)
  • 注意:未定义的偏移量:PHP(Notice: Undefined offset: PHP)
  • 如何读R中的大数据集[复制](How to read large dataset in R [duplicate])
  • Unity 5 Heighmap与地形宽度/地形长度的分辨率关系?(Unity 5 Heighmap Resolution relationship to terrain width / terrain length?)
  • 如何通知PipedOutputStream线程写入最后一个字节的PipedInputStream线程?(How to notify PipedInputStream thread that PipedOutputStream thread has written last byte?)
  • python的访问器方法有哪些
  • DeviceNetworkInformation:哪个是哪个?(DeviceNetworkInformation: Which is which?)
  • 在Ruby中对组合进行排序(Sorting a combination in Ruby)
  • 网站开发的流程?
  • 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
  • 条带格式类型格式模式编号无法正常工作(Stripes format type format pattern number not working properly)
  • 透明度错误IE11(Transparency bug IE11)
  • linux的基本操作命令。。。