随笔- 509  文章- 0  评论- 151  阅读- 22万 

2014-05-10 22:30

题目链接

原题:

Design database locks to allow r/w concurrency and data consistency.

题目:设计一个支持并行读写并保证数据一致性的数据库锁。

解法:这是什么范畴的面试题?对于我这种完全没有相关项目经验的人,还真是无从下手。翻了书之后顺便重新复习了一下共享锁、互斥锁的概念。说白了,这些都是课本上的基础知识,可是毕业没多久就忘光了。看来知识不用,保质期比水果还短。然后我琢磨着锁的模型,写了个模拟的代码。这个代码和SQL毫无关系,可能也和正确答案相去甚远。姑妄言之,姑妄听之吧。

代码:

复制代码
 1 // http://www.careercup.com/question?id=6366101810184192
 2 import java.util.concurrent.Semaphore;
 3 
 4 public class FooBar {
 5     public static final int MAX_CONCURRENT_READ = 100;
 6     private Semaphore sharedSemaphore;
 7     private Semaphore exclusiveSemaphore;
 8 
 9     public FooBar() {
10         // TODO Auto-generated constructor stub
11         this.sharedSemaphore = new Semaphore(MAX_CONCURRENT_READ);
12         this.exclusiveSemaphore = new Semaphore(1);
13     }
14 
15     public void reader() {
16         // The reader here is not to return a value, but to perform read()
17         // action. Thus it is 'void reader()'.
18         while (exclusiveSemaphore.availablePermits() < 1) {
19             try {
20                 Thread.sleep(50);
21             } catch (InterruptedException e) {
22                 // TODO Auto-generated catch block
23                 e.printStackTrace();
24             }
25         }
26 
27         try {
28             sharedSemaphore.acquire();
29             System.out.println("Performing read() operation.");
30             sharedSemaphore.release();
31         } catch (InterruptedException e) {
32             // TODO Auto-generated catch block
33             e.printStackTrace();
34         }
35     }
36 
37     public void writer() {
38         while (exclusiveSemaphore.availablePermits() < 1
39                 && sharedSemaphore.availablePermits() < MAX_CONCURRENT_READ) {
40             try {
41                 Thread.sleep(50);
42             } catch (InterruptedException e) {
43                 // TODO Auto-generated catch block
44                 e.printStackTrace();
45             }
46         }
47 
48         try {
49             exclusiveSemaphore.acquire();
50             System.out.println("Performing write() operation.");
51             exclusiveSemaphore.release();
52         } catch (InterruptedException e) {
53             // TODO Auto-generated catch block
54             e.printStackTrace();
55         }
56     }
57 
58     public static void main(String[] args) {
59         FooBar fooBar = new FooBar();
60 
61         fooBar.reader();
62         fooBar.writer();
63     }
64 }
复制代码

 

 posted on   zhuli19901106  阅读(169)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示