首页 \ 问答 \ 是否适合使用AtomicReference.compareAndSet来设置对数据库调用结果的引用?(Is it appropriate to use AtomicReference.compareAndSet to set a reference to the results of a database call?)

是否适合使用AtomicReference.compareAndSet来设置对数据库调用结果的引用?(Is it appropriate to use AtomicReference.compareAndSet to set a reference to the results of a database call?)

我正在实现一个简单的缓存,缓存存储为AtomicReference。

private AtomicReference<Map<String, String>> cacheData;

应该从数据库表中填充(延迟)缓存对象。

我提供了一种方法来将缓存数据返回给调用者,但如果数据为空(即未加载),则代码需要从数据库加载数据。 为避免同步我想到使用compareAndSet()方法:

public Object getCacheData() {
  cacheData.compareAndSet(null, getDataFromDatabase()); // atomic reload only if data not set!
  return Collections.unmodifiableMap(cacheData.get());
}

以这种方式使用compareAndSet是否可以。 将数据库调用作为原子操作的一部分? 是否比同步方法更好/更差?

非常感谢任何建议..


I am implementing a simple cache with the cache stored as an AtomicReference.

private AtomicReference<Map<String, String>> cacheData;

The cache object should be populated (lazily) from a database table.

I provide a method to return the cache data to a caller, but if the data is null (ie. not loaded), then the code needs to load the data from the database. To avoid synchronized I thought of using the compareAndSet() method:

public Object getCacheData() {
  cacheData.compareAndSet(null, getDataFromDatabase()); // atomic reload only if data not set!
  return Collections.unmodifiableMap(cacheData.get());
}

Is it ok to use compareAndSet in this way ie. to involve a database call as part of the atomic action? Is it any better/worse than just synchronizing the method?

Many thanks for any advice..


原文:https://stackoverflow.com/questions/12992478
更新时间:2023-11-10 09:11

最满意答案

布局:

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="android.sample.MainActivity">

<TextView
    android:id="@+id/txtFont_size_hint"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Sizes"/>
<LinearLayout
    android:id="@+id/ll"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="10dp"
    android:weightSum="5">

        <LinearLayout
    android:id="@+id/ll"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:weightSum="5">

    <TextView
        android:id="@+id/txtSize1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center"
        android:text="@string/setting_font_text"
        android:textSize="15sp"/>

    <TextView
        android:id="@+id/txtSize_18"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center"
        android:text="@string/setting_font_text"
        android:textSize="20sp"/>

    <TextView
        android:id="@+id/txtSize_24"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:focusable="false"
        android:gravity="center"
        android:text="@string/setting_font_text"
        android:textSize="25sp"/>

    <TextView
        android:id="@+id/textSize_30"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:focusable="false"
        android:gravity="center"
        android:text="@string/setting_font_text"
        android:textSize="30sp"/>

    <TextView
        android:id="@+id/txtSize_36"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:focusable="false"
        android:gravity="center"
        android:text="@string/setting_font_text"
        android:textSize="35sp"/>
</LinearLayout>

<SeekBar
    android:id="@+id/seekBarSetting_font_size"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:max="4"/>

现在我所做的是将Seekbar的宽度对齐到最后一个TextView的中心,在这种情况下是txtSize_36并将ems设置为android:max="4"所以有五个可能的值(你可以将其更改为你想要的很多)

活动代码是:

public class MainActivity extends AppCompatActivity {
SeekBar seekBar;

private LinearLayout bar, ll;
TextView txtSize_14, txtSize_36;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    seekBar = (SeekBar) findViewById(R.id.seekBarSetting_font_size);

    txtSize_14 = (TextView) findViewById(R.id.txtSize1);
    txtSize_36 = (TextView) findViewById(R.id.txtSize_36);
    ll = (LinearLayout) findViewById(R.id.ll);

}
    float density;
    @Override
    protected void onResume() {
    super.onResume();

    ViewTreeObserver vto = ll.getViewTreeObserver();
//****old code (may not work on all orientations)****
/*vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
                ll.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            } else {
                ll.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            }
            int width  = ll.getMeasuredWidth();
            int height = ll.getMeasuredHeight();

            ViewGroup.LayoutParams params = seekBar.getLayoutParams();

            density = getResources().getDisplayMetrics().density;
            int newwidth = (int) (txtSize_14.getLeft() / density);
            newwidth = newwidth+ (txtSize_36.getLeft() + txtSize_36.getRight()) / 2;
            params.width = newwidth;
            seekBar.setLayoutParams(params);

        }
    });*/

    //****new code (should work on all orientations)****
vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
                ll.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            } else {
                ll.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            }
            seekBar.setPadding(15, 0, 15, 0);
            seekBar.setX(((txtSize_14.getLeft() + txtSize_14.getRight()) / 2) - 15);

            ViewGroup.LayoutParams params = seekBar.getLayoutParams();

            int centerwidth = ((txtSize_36.getLeft() + txtSize_36.getRight()) / 2) - ((txtSize_14.getLeft() + txtSize_14.getRight()) / 2) + 15;
            params.width = centerwidth;
            seekBar.setLayoutParams(params);
        }
    });

}

}

这是截图供参考(我已经为搜索栏的所有位置添加了棒球): 在此处输入图像描述


layout for this :

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="android.sample.MainActivity">

<TextView
    android:id="@+id/txtFont_size_hint"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Sizes"/>
<LinearLayout
    android:id="@+id/ll"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="10dp"
    android:weightSum="5">

        <LinearLayout
    android:id="@+id/ll"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:weightSum="5">

    <TextView
        android:id="@+id/txtSize1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center"
        android:text="@string/setting_font_text"
        android:textSize="15sp"/>

    <TextView
        android:id="@+id/txtSize_18"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center"
        android:text="@string/setting_font_text"
        android:textSize="20sp"/>

    <TextView
        android:id="@+id/txtSize_24"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:focusable="false"
        android:gravity="center"
        android:text="@string/setting_font_text"
        android:textSize="25sp"/>

    <TextView
        android:id="@+id/textSize_30"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:focusable="false"
        android:gravity="center"
        android:text="@string/setting_font_text"
        android:textSize="30sp"/>

    <TextView
        android:id="@+id/txtSize_36"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:focusable="false"
        android:gravity="center"
        android:text="@string/setting_font_text"
        android:textSize="35sp"/>
</LinearLayout>

<SeekBar
    android:id="@+id/seekBarSetting_font_size"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:max="4"/>

Now what i have done is aligned the width of Seekbar till the center of the last TextView which in this case is txtSize_36 and have set the ems as android:max="4" so there are five possible values(you can change this to as much as you want)

Code for Activity is :

public class MainActivity extends AppCompatActivity {
SeekBar seekBar;

private LinearLayout bar, ll;
TextView txtSize_14, txtSize_36;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    seekBar = (SeekBar) findViewById(R.id.seekBarSetting_font_size);

    txtSize_14 = (TextView) findViewById(R.id.txtSize1);
    txtSize_36 = (TextView) findViewById(R.id.txtSize_36);
    ll = (LinearLayout) findViewById(R.id.ll);

}
    float density;
    @Override
    protected void onResume() {
    super.onResume();

    ViewTreeObserver vto = ll.getViewTreeObserver();
//****old code (may not work on all orientations)****
/*vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
                ll.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            } else {
                ll.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            }
            int width  = ll.getMeasuredWidth();
            int height = ll.getMeasuredHeight();

            ViewGroup.LayoutParams params = seekBar.getLayoutParams();

            density = getResources().getDisplayMetrics().density;
            int newwidth = (int) (txtSize_14.getLeft() / density);
            newwidth = newwidth+ (txtSize_36.getLeft() + txtSize_36.getRight()) / 2;
            params.width = newwidth;
            seekBar.setLayoutParams(params);

        }
    });*/

    //****new code (should work on all orientations)****
vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
                ll.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            } else {
                ll.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            }
            seekBar.setPadding(15, 0, 15, 0);
            seekBar.setX(((txtSize_14.getLeft() + txtSize_14.getRight()) / 2) - 15);

            ViewGroup.LayoutParams params = seekBar.getLayoutParams();

            int centerwidth = ((txtSize_36.getLeft() + txtSize_36.getRight()) / 2) - ((txtSize_14.getLeft() + txtSize_14.getRight()) / 2) + 15;
            params.width = centerwidth;
            seekBar.setLayoutParams(params);
        }
    });

}

}

Here is screenshot for reference (I have clubbed for all positions of seekbar): enter image description here

相关问答

更多

相关文章

更多

最新问答

更多
  • h2元素推动其他h2和div。(h2 element pushing other h2 and div down. two divs, two headers, and they're wrapped within a parent div)
  • 创建一个功能(Create a function)
  • 我投了份简历,是电脑编程方面的学徒,面试时说要培训三个月,前面
  • PDO语句不显示获取的结果(PDOstatement not displaying fetched results)
  • Qt冻结循环的原因?(Qt freezing cause of the loop?)
  • TableView重复youtube-api结果(TableView Repeating youtube-api result)
  • 如何使用自由职业者帐户登录我的php网站?(How can I login into my php website using freelancer account? [closed])
  • SQL Server 2014版本支持的最大数据库数(Maximum number of databases supported by SQL Server 2014 editions)
  • 我如何获得DynamicJasper 3.1.2(或更高版本)的Maven仓库?(How do I get the maven repository for DynamicJasper 3.1.2 (or higher)?)
  • 以编程方式创建UITableView(Creating a UITableView Programmatically)
  • 如何打破按钮上的生命周期循环(How to break do-while loop on button)
  • C#使用EF访问MVC上的部分类的自定义属性(C# access custom attributes of a partial class on MVC with EF)
  • 如何获得facebook app的publish_stream权限?(How to get publish_stream permissions for facebook app?)
  • 如何防止调用冗余函数的postgres视图(how to prevent postgres views calling redundant functions)
  • Sql Server在欧洲获取当前日期时间(Sql Server get current date time in Europe)
  • 设置kotlin扩展名(Setting a kotlin extension)
  • 如何并排放置两个元件?(How to position two elements side by side?)
  • 如何在vim中启用python3?(How to enable python3 in vim?)
  • 在MySQL和/或多列中使用多个表用于Rails应用程序(Using multiple tables in MySQL and/or multiple columns for a Rails application)
  • 如何隐藏谷歌地图上的登录按钮?(How to hide the Sign in button from Google maps?)
  • Mysql左连接旋转90°表(Mysql Left join rotate 90° table)
  • dedecms如何安装?
  • 在哪儿学计算机最好?
  • 学php哪个的书 最好,本人菜鸟
  • 触摸时不要突出显示表格视图行(Do not highlight table view row when touched)
  • 如何覆盖错误堆栈getter(How to override Error stack getter)
  • 带有ImageMagick和许多图像的GIF动画(GIF animation with ImageMagick and many images)
  • USSD INTERFACE - > java web应用程序通信(USSD INTERFACE -> java web app communication)
  • 电脑高中毕业学习去哪里培训
  • 正则表达式验证SMTP响应(Regex to validate SMTP Responses)