ziggle

Hail Hydra


  • Home

  • Archives

  • Search

stackoverflow-question

Posted on 2018-04-12

一行初始化ArrayList

1
2
3
4
5
6
7
ArrayList<String> places = new ArrayList<String>(){{
add("A");
add("B");
add("C");
}};

List<String> places = Arrays.asList("Buenos Aires", "Córdoba", "La Plata");

使用maven创建带依赖的可执行jar

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<build>
<plugins>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<archive>
<manifest>
<mainClass>fully.qualified.MainClass</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
</plugins>
</build>
<build>
<plugins>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<archive>
<manifest>
<mainClass>fully.qualified.MainClass</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
</plugins>
</build>

and run

mvn clean compile assembly:single

判断数组是否包含指定元素

1
2
int[] a = [1,2,3,4,5];
boolean contains = IntStream.of(a).anyMatch(x->x==3);
Read more »

differences_between_hashmap_and_hashtable

Posted on 2018-04-08

线程
hashtable 是同步的 相反 hashmap并不是,
null
hashtable 不允许有nullkey 或value ,hashmap 运行有一个null key 和任意个null value
iterator
hashmap的子类linkedhashmap 迭代出的元素按插入顺序 可以有hashmap -> linkedhashmap 获取有序遍历

为什么使用char[] 保存password 而不是 String

string 类型是不可变类型,当创建String 实例对象,如果另一个进程dump 内存,是没法清除创建的string (在gc介入之前),如果用char[] 可以显式wrap数据
减少了password 被attack ….

java concurrent 包实现

线程间通信有四种方式
A线程写volatile变量,随后B线程读这个volatile变量。
A线程写volatile变量,随后B线程用CAS更新这个volatile变量。
A线程用CAS更新一个volatile变量,随后B线程用CAS更新这个volatile变量。
A线程用CAS更新一个volatile变量,随后B线程读这个volatile变量。

volatile变量的读/写和CAS可以实现线程之间的通信 => java concurrent包的基石

分析HashMap的put方法

①.判断键值对数组 table[i] 是否为空或为 null,否则执行 resize() 进行扩容;

②.根据键值 key 计算 hash 值得到插入的数组索引i,如果 table[i]==null,直接新建节点添加,转向 ⑥,如果table[i] 不为空,转向 ③;

③.判断 table[i] 的首个元素是否和 key 一样,如果相同直接覆盖 value,否则转向 ④,这里的相同指的是 hashCode 以及 equals;

④.判断table[i] 是否为 treeNode,即 table[i] 是否是红黑树,如果是红黑树,则直接在树中插入键值对,否则转向 ⑤;

⑤.遍历 table[i],判断链表长度是否大于 8,大于 8 的话把链表转换为红黑树,在红黑树中执行插入操作,否则进行链表的插入操作;遍历过程中若发现 key 已经存在直接覆盖 value 即可;

⑥.插入成功后,判断实际存在的键值对数量 size 是否超多了最大容量 threshold,如果超过,进行扩容。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
public V put(K key, V value) {
// 对key的hashCode()做hash
return putVal(hash(key), key, value, false, true);
}

final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
// 步骤①:tab为空则创建
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
// 步骤②:计算index,并对null做处理
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
// 步骤③:节点key存在,直接覆盖value
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
// 步骤④:判断该链为红黑树
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
// 步骤⑤:该链为链表
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key,value,null);
//链表长度大于8转换为红黑树进行处理
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
// key已经存在直接覆盖value
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}

if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
// 步骤⑥:超过最大容量 就扩容
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}

exceptionhandler

Posted on 2018-04-04

在task执行完处理异常

处理异常1

1
2
3
4
5
6
7
8
9
10
11
12

var task1 = Task.Run(() =>
{
Console.WriteLine(1223);
// throw new CustomException("task1 faulted.");
}).ContinueWith(t => {
Console.WriteLine("{0}: {1}",
t.Exception.InnerException.GetType().Name,
t.Exception.InnerException.Message);
}, TaskContinuationOptions.OnlyOnFaulted);
Thread.Sleep(500);
// 当发生异常时执行ContinueWith

在task执行结束 主线程内处理异常

处理异常2

1
2
3
var tt = Task.Factory.StartNew(() => throw new ArgumentException());
while (!tt.IsCompleted){} // tt.Wait()
var excoCollection = tt.Exception?.InnerExceptions;

处理异常3

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var task1 = Task.Run(() => { throw new CustomException("This exception is expected!"); });
while (!task1.IsCompleted) { }
if (task1.Status == TaskStatus.Faulted)
{
foreach (var e in task1.Exception.InnerExceptions)
{
// 处理自定义异常
if (e is CustomException)
{
Console.WriteLine(e.Message);
}
// 抛去其他异常
else{throw e;}
}
}

如果不想等到task结束

sql调优

Posted on 2018-03-16

连接优化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
--before
SELECT
*
FROM
(
SELECT
TOP 15 *
FROM
zbjm_comment WITH (nolock)
WHERE
AuditStatus = 1
AND IsDeleted = 0
AND path LIKE '1:0000000000000000059-0000000000000107656%'
ORDER BY
Id
) a0
UNION ALL
SELECT
*
FROM
(
SELECT
TOP 15 *
FROM
zbjm_comment WITH (nolock)
WHERE
AuditStatus = 1
AND IsDeleted = 0
AND path LIKE '1:0000000000000000059-0000000000000003369%'
ORDER BY
Id
) a10
-- after

DECLARE @@temp TABLE (path VARCHAR(MAX)) INSERT INTO @@temp
VALUES ('1:0000000000000000059-0000000000000107656%'),
('1:0000000000000000059-0000000000000087470%'),
('1:0000000000000000059-0000000000000040167%'),
('1:0000000000000000059-0000000000000004254%'),

('1:0000000000000000059-0000000000000003377%'),
('1:0000000000000000059-0000000000000003369%')
SELECT
c.[Id],
c.[UserId],
c.[NickName],
c.[Avatar],
c.[TargetType],
c.[TargetId],
c.[Path],
c.[CommentContent],
c.[AuditStatus],
c.[PraiseCount],
c.[CreationTime],
c.[ModificationTime],
c.[IsDeleted]
FROM
zbjm_comment c WITH (
nolock,
INDEX = [NonClusteredIndex-Path]
)
JOIN @@temp t ON c.path LIKE t.path -- 此处c 表path 建立非聚集索引
WHERE
c.auditstatus = 1
AND c.isdeleted = 0

插入时去重 insert

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
INSERT INTO dbo.Learn_CouponSendJob (
UserId,
NickName,
AddTime,
IsDeleted,
SendId,
CouponId,
IsNotice,
SendTime,
SendStatus,
SendToId
) SELECT
t1.*
FROM
(
SELECT
Id AS UserId,
NickName AS NickName,
GetDate() AS AddTime,
0 AS IsDeleted,
43 AS SendId,
3 AS CouponId,
0 AS IsNotice ,GETDATE() AS SendTime,
1 AS SendStatus ,- 1 AS SendToId
FROM
Learn_User WITH (NOLOCK)
WHERE
Status = 1
AND Id IN (152)
) t1
LEFT JOIN dbo.Learn_CouponSendJob t2 ON t1.UserId = t2.UserId
AND t1.SendId = t2.SendId
AND t1.SendToId = t2.SendToId
WHERE
t2.id IS NULL
Read more »

redis

Posted on 2018-03-14

使用redis 保存文章信息
文章包括标题、作者、赞数等信息,在关系型数据库中很容易构建一张表来存储这些信息,在 Redis 中可以使用 HASH 来存储每种信息以及其对应的值的映射。

Redis 没有表的概念将同类型的数据存放在一起,而是使用命名空间的方式来实现这一功能。键名的前面部分存储命名空间,后面部分的内容存储 ID,通常使用 : 来进行分隔。例如下面的 HASH 的键名为 article:92617,其中 article 为命名空间,ID 为 92617。

Redis UDS

Lettuce还支持使用Unix Domain Sockets, 这对程序和Redis在同一机器上的情况来说,是一大福音。平时我们连接应用和数据库如Mysql,都是基于TCP/IP套接字的方式,如127.0.0.1:3306,达到进程与进程之间的通信,Redis也不例外。但使用UDS传输不需要经过网络协议栈,不需要打包拆包等操作,只是数据的拷贝过程,也不会出现丢包的情况,更不需要三次握手,因此有比TCP/IP更快的连接与执行速度。当然,仅限Redis进程和程序进程在同一主机上,而且仅适用于Unix及其衍生系统。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
private RedisURI createRedisURI() {
Builder builder = null;
// 判断是否有配置UDS信息,以及判断Redis是否有支持UDS连接方式,是则用UDS,否则用TCP
if (StringUtils.isNotBlank(socket) && Files.exists(Paths.get(socket))) {
builder = Builder.socket(socket);
System.out.println("connect with Redis by Unix domain Socket");
log.info("connect with Redis by Unix domain Socket");
} else {
builder = Builder.redis(hostName, port);
System.out.println("connect with Redis by TCP Socket");
log.info("connect with Redis by TCP Socket");
}
builder.withDatabase(dbIndex);
if (StringUtils.isNotBlank(password)) {
builder.withPassword(password);
}
return builder.build();
}
1…151617…22
ziggle

ziggle

Hail Hydra !

110 posts
45 tags
RSS
GitHub
© 2021 ziggle
Powered by Hexo
|
Hail Hydra—